Here is my javascript code
for (var i = 1; i <= _MAXPAGECOUNT - 2; i++) {
e = document.getElementsByName("q" + i + "[]");
for (var j = 0; j <= e.length - 1; j++) {
if (e[j].checked) {
result = result + "," + i + ":" + e[j].value;
// break;
}
}}
The problem is this, it shows result like this 1:2,1:3,1:4,2:3,2:4,2:5
here in code i means question number and j means answer number, but I want to result as like this 1:2,3,4 ; 2:3,4,5
Try this
for (var i = 1; i <= _MAXPAGECOUNT - 2; i++) {
result = result+i+":";
e = document.getElementsByName("q" + i + "[]");
for (var j = 0; j <= e.length - 1; j++) {
if (e[j].checked) {
result = result + e[j].value;
// break;
}
}
if(i<_MAXPAGECOUNT - 2)
{
result = result+" ; ";
}
}
Related
How could I create Pyramide of Stars that increase every row by 2 like that:
*
* * *
* * * * *
* * * * * * *
My currently code:
for (var x = 0; x < 5; x++) {
for (var y = 0; y <= x; y = y + 1) {
document.write(" * ");
}
document.write("<br>");
}
It's possible just to increment in your loop by 2.
for(var i = 1; i < 20; i += 2) {
console.log( Array(i).fill('*').join(' ') );
}
Otherwise just multiply inside your loop
for(var i = 0; i < 10; i++) {
console.log( Array(i*2 + 1).fill('*').join(' ') );
}
You may also need to polyfill Array.fill depending on your target.
Other answers recreate the entire row each time. This solution just extends the row each time to have another star.
function pyramid(n) {
let result = '', str = '', add = '*';
for (var i = 0; i < n; i++) {
str += add;
add = ' *';
if (!(i % 2)) result += str + '\n';
}
return result;
}
console.log(pyramid(5));
You can do like this.
function generate() {
var totalNumberofRows = 5;
var output="";
for (var i = 1; i <= totalNumberofRows; i++) {
for (var j = 1; j <= i; j++) {
if(j==1)
output+="*";
else
output+=" "+ "*" + " "+ "*";
}
console.log(output);
output="";
}
}
generate()
Hope so this is also beneficial for you....
$(document).ready(function () {
var NumberofRows = 5,arr;
for (var i = 1; i <= NumberofRows; i++) {
pyramid = [];
for (var j = 1; j <= i; j++) {
pyramid.push('*');
}
console.log(pyramid.join(" ") + "\n");
}
});
``
i am using javascript nested loops and i need to break second loop on some condition but only second loop not the first one can anybody tell me how is it possible
my code
var myVar = "";
var i, j;
loopone:
for (i = 0; i < 3; i++) {
text += "<br>" + "i = " + i + ", j = ";
looptwo:
for (j = 10; j < 15; j++) {
if (j === 12) {
break;
}
document.getElementById("demo").innerHTML = text += j + " ";
}
}
not this break statement stop both loops but i want to stop only second loop.
Any help would be appriciated. thanks in advance!
Well its so simple of you are using loops with label then you just have to mention the label(loop name) after break statement like this
var myVar = "";
var i, j;
loopone:
for (i = 0; i < 3; i++) {
text += "<br>" + "i = " + i + ", j = ";
looptwo:
for (j = 10; j < 15; j++) {
if (j === 12) {
break looptwo;
}
document.getElementById("demo").innerHTML = text += j + " ";
}
}
this will break only loop with name looptwo
Ok i finally got my minesweeper game made just needing one more thing if anyone could help me with. The part when you click on an unnumbered square and it will reveal some of the board. I have been playing around on this for sometime just drawing a blank. This is a simple minesweeper game just in java script. I have everything labeled where things should go to make it easier to find and i will bold it on where my code ive been working on is.
//Global
//store the value of each square
var gaValue = new Array(8)
for (i = 0; i <= 8; i++)
gaValue[i] = new Array(8)
for (i = 0; i <= 8; i++)
{
//loop through each item in those row
for (j = 0; j <= 8 ; j++)
gaValue[i][j] = 0
}
//Store the status of each square
var gaSquare = new Array(8)
for (j = 0; j <= 8; j++)
gaSquare[j] = new Array(8)
for (j = 0; j <= 8; j++)
{
//loop through each item in those row
for (i = 0; i <= 8 ; i++)
gaSquare[i][j] = "C"
}
//Track of whether the game is over or not (starts this with false)
var gbGameOver = false
function vInit()
{
var strHTML
var i
var j
strHTML = "<table style='margin-left:auto;margin-right:auto'>"
strHTML += "<tr><td colspan='8' style='text-align:center'>MineSweeper</td></tr>"
strHTML += "<tr><td colspan='8' style='text-align:center'><input type='button' id='btnNew' value='New Game' onclick='vNewGame()'></td></tr>"
//Loop through the rows to build the table of tiles
for (i = 0; i < 8; i++)
{
strHTML += "<tr>"
for (j = 0; j < 8; j++)
strHTML += '<td><img src="images/sqt0.png" id="square' + i + ', ' + j + '" onclick="vClick(' + i + ', ' + j + ')"/></td>';
strHTML += "<tr>";
}
strHTML += '<tr><td colspan="8" style="text-align:center"><textarea id="taOut" cols="18" rows="10"></textarea></td></tr>'
strHTML += "</table>"
frmGrid.innerHTML = strHTML
//Place bombs
var iBomb = 0
var iRow = Math.floor(Math.random() * 8)
var iCol = Math.floor(Math.random() * 8)
while (iBomb < 8)
{
while (gaValue[iRow][iCol] == 9)
{
iRow = Math.floor(Math.random() * 8)
iCol = Math.floor(Math.random() * 8)
}
gaValue[iRow][iCol] = 9
iBomb++
}
//Calculate clue values around mines
var iMine = 0
for (i = 0; i < 8; i++)
{
for (j = 0; j < 8; j++)
{
for (k = (i - 1) ; k <= (i + 1) ; k++)
for (m = (j - 1) ; m <= (j + 1) ; m++)
if (k >= 0 && k <= 9 && j >= 0 && j <= 9)
if (gaValue[k][m] == 9)
iMine++
if (gaValue[i][j] != 9)
gaValue[i][j] = iMine
iMine = 0
}
}
}
//Get the ID of the image I need to change
function vClick(iRow, iCol)
{
var gaSquare = "square" + iRow + ", " + iCol
var strOut = ""
gaSquare[iRow][iCol] = 'o';
document.getElementById(gaSquare).src = "images/" + gaValue[iRow][iCol] + ".png"
if (gaValue[iRow][iCol] == 9)
{
gbGameOver = true
strOut = "Game Over"
vOver()
}
else if (gaValue[iRow][iCol] == 0)
vZero(iRow, iCol)
document.getElementById('taOut').value = strOut
}
//GameOver
function vOver()
{
var i
var j
var strID;
for (i = 0; i < 8; i++)
for (j = 0; j < 8; j++) {
strID = "square" + i + ", " + j;
document.getElementById(strID).src = "images/" + gaValue[i][j] + ".png"
}
}
**//Clearing area
function vZero(iRow, iCol, i, j) {
for (i = iRow - 1; i <= iRow + 1; i++) {
for (j = iCol - 1; j <= iCol + 1; j++) {
if (k >= 0 && k <= 8 && j >= 0 && j <= 8)
vClick(i, j)
}**
//Start new game
function vNewGame() {
vInit()
}
//no menu on right click
function bIsRightButtonClicked(e) {
var rightclick = false
e = e || window.event
if (e.which) {
rightclick = (e.which == 3)
}
else if (e.button) {
rightclick = (e.button == 2)
}
return rightclick
}
}
}
I believe the main mistake is that you are referring to k inside vZero() when that variable is not defined. You also appear to be missing a closing curly bracket or two on that function.
Try changing that function to as follows:
//Clearing area
function vZero(iRow, iCol) {
for (var i = iRow - 1; i <= iRow + 1; i++) {
for (var j = iCol - 1; j <= iCol + 1; j++) {
if (i >= 0 && i <= 8 && j >= 0 && j <= 8) vClick(i, j);
}
}
}
You'll note that I changed the i and j parameters to be local variables, because they are only used by that function for the purposes of the for loops. You don't need to have them as parameters. Doing so only confuses other developers because that implies that you need to pass a value for them into the function for it to work, whereas you only need to pass in iRow and iCol. Does that make sense?
I'm creating a form where users can input a range. They are allowed to input letters and numbers. Some sample input:
From: AA01
To: AZ02
Which should result in:
AA01
AA02
AB01
AB02
And so on, till AZ02
And:
From: BC01
To: DE01
Should result in:
BC01
BD01
BE01
CC01
CD01
CE01
Etc
I managed to get it working for the input A01 to D10 (for example)
jsFiddle
However, i can't get it to work with multiple letters.
JS code:
var $from = $('input[name="from"]');
var $to = $('input[name="to"]');
var $quantity = $('input[name="quantity"]');
var $rangeList = $('.rangeList');
var $leadingzeros = $('input[name="leadingzeros"]');
$from.on('keyup blur', function () {
$(this).val($(this).val().replace(/[^a-zA-Z0-9]/g, ''));
updateQuantity();
});
$to.on('keyup blur', function () {
$(this).val($(this).val().replace(/[^a-zA-Z0-9]/g, ''));
updateQuantity();
});
$leadingzeros.on('click', function () {
updateQuantity();
});
function updateQuantity() {
var x = parseInt($from.val().match(/\d+/));
var y = parseInt($to.val().match(/\d+/));
var xl = $from.val().match(/[a-zA-Z]+/);
var yl = $to.val().match(/[a-zA-Z]+/);
var result = new Array();
if (xl != null && yl != null && xl[0].length > 0 && yl[0].length > 0) {
xl = xl[0].toUpperCase();
yl = yl[0].toUpperCase();
$rangeList.html('');
var a = yl.charCodeAt(0) - xl.charCodeAt(0);
for (var i = 0; i <= a; i++) {
if (!isNaN(x) && !isNaN(y)) {
if (x <= y) {
var z = (y - x) + 1;
$quantity.val(z * (a + 1));
$rangeList.html('');
for (var b = z; b > 0; b--) {
var c = ((y - b) + 1);
if ($leadingzeros.prop('checked')) {
c = leadingZeroes(c, y.toString().length);
}
result.push(String.fromCharCode(65 + i) + c);
}
} else {
$rangeList.html('');
$quantity.val(0);
}
} else {
$rangeList.html('');
$quantity.val(0);
}
}
} else if (!isNaN(x) && !isNaN(y)) {
if (x < y) {
var z = (y - x) + 1;
$quantity.val(z);
$rangeList.html('');
for (var i = z; i > 0; i--) {
var c = (y - i) + 1;
if ($leadingzeros.prop('checked')) {
c = leadingZeroes(c, y.toString().length);
}
result.push(c);
}
} else {
$rangeList.html('');
$quantity.val(0);
}
} else {
$rangeList.html('');
$quantity.val(0);
}
$rangeList.html('');
for (var i = 0; i < result.length; i++) {
$rangeList.append(result[i] + '<br />');
}
}
function leadingZeroes(number, size) {
number = number.toString();
while (number.length < size) number = "0" + number;
return number;
}
This is perfect for a recursive algorithm:
function createRange(from, to) {
if (from.length === 0) {
return [ "" ];
}
var result = [];
var innerRange = createRange(from.substring(1), to.substring(1));
for (var i = from.charCodeAt(0); i <= to.charCodeAt(0); i++) {
for (var j = 0; j < innerRange.length; j++) {
result.push(String.fromCharCode(i) + innerRange[j]);
}
}
return result;
}
Called as follows:
createRange('BC01', 'DE02'); // Generates an array containing all values expected
EDIT: Amended function below to match new test case (much more messy, however, involving lots of type coercion between strings and integers).
function prefixZeroes(value, digits) {
var result = '';
value = value.toString();
for (var i = 0; i < digits - value.length; i++) {
result += '0';
}
return result + value;
}
function createRange(from, to) {
if (from.length === 0) {
return [ "" ];
}
var result = [];
if (from.charCodeAt(0) < 65) {
fromInt = parseInt(from);
toInt = parseInt(to);
length = toInt.toString().length;
var innerRange = createRange(from.substring(length), to.substring(length));
for (var i = fromInt; i <= toInt; i++) {
for (var j = 0; j < innerRange.length; j++) {
result.push(prefixZeroes(i, length) + innerRange[j]);
}
}
} else {
var innerRange = createRange(from.substring(1), to.substring(1));
for (var i = from.charCodeAt(0); i <= to.charCodeAt(0); i++) {
for (var j = 0; j < innerRange.length; j++) {
result.push(String.fromCharCode(i) + innerRange[j]);
}
}
}
return result;
}
Please note that because of your strict logic in how the value increments this method requires exactly 4 characters (2 letters followed by 2 numbers) to work. Also, this might not be as efficient/tidy as it can be but it took some tinkering to meet your logic requirements.
function generate(start, end) {
var results = [];
//break out the start/end letters/numbers so that we can increment them seperately
var startLetters = start[0] + start[1];
var endLetters = end[0] + end[1];
var startNumber = Number(start[2] + start[3]);
var endNumber = Number(end[2] + end[3]);
//store the start letter/number so we no which value to reset the counter to when a maximum boundry in reached
var resetLetter = startLetters[1];
var resetNumber = startNumber;
//add first result as we will always have at least one
results.push(startLetters + (startNumber < 10 ? "0" + startNumber : "" + startNumber));
//maximum while loops for saefty, increase if needed
var whileSafety = 10000;
while (true) {
//safety check to ensure while loop doesn't go infinite
whileSafety--;
if (whileSafety == 0) break;
//check if we have reached the maximum value, if so stop the loop (break)
if (startNumber == endNumber && startLetters == endLetters) break;
//check if we have reached the maximum number. If so, and the letters limit is not reached
//then reset the number and increment the letters by 1
if (startNumber == endNumber && startLetters != endLetters) {
//reset the number counter
startNumber = resetNumber;
//if the second letter is at the limit then reset it and increment the first letter,
//otherwise increment the second letter and continue
if (startLetters[1] == endLetters[1]) {
startLetters = '' + String.fromCharCode(startLetters.charCodeAt(0) + 1) + resetLetter;
} else {
startLetters = startLetters[0] + String.fromCharCode(startLetters.charCodeAt(1) + 1);
}
} else {
//number limit not reached so just increment the number counter
startNumber++;
}
//add the next sequential value to the array
results.push(startLetters + (startNumber < 10 ? "0" + startNumber : "" + startNumber));
}
return results;
}
var results = generate("BC01", "DE01");
console.log(results);
Here is a working example, which uses your second test case
Using #Phylogenesis' code, i managed to achieve my goal.
jsFiddle demo
function updateQuantity() {
var x = parseInt($from.val().match(/\d+/));
var y = parseInt($to.val().match(/\d+/));
var xl = $from.val().match(/[a-zA-Z]+/);
var yl = $to.val().match(/[a-zA-Z]+/);
var result = new Array();
var r = createRange(xl[0], yl[0]);
var z = (y - x) + 1;
if (x <= y) {
for (var j = 0; j < r.length; j++) {
var letters = r[j];
for (var i = z; i > 0; i--) {
var c = (y - i) + 1;
if ($leadingzeros.prop('checked')) {
c = leadingZeroes(c, y.toString().length);
}
if (i == z) {
r[j] = letters + c + '<br />';
} else {
j++;
r.splice(j, 0, letters + c + '<br />');
}
}
}
} else {
for (var i = 0; i < r.length; i++) {
r[i] += '<br />';
}
}
$quantity.val(r.length);
$rangeList.html('');
for (var i = 0; i < r.length; i++) {
$rangeList.append(r[i]);
}
}
This works for unlimited letters and numbers, as long as the letters are first.
Thanks for your help!
How can I check for matching numbers in this script, stuck here, I need to compare the array of user numbers with the array of lotto numbers and display how many numbers they got correct if any along with their prize value.
function numbers() {
var numbercount = 6;
var maxnumbers = 40;
var ok = 1;
r = new Array(numbercount);
for (var i = 1; i <= numbercount; i++) {
r[i] = Math.round(Math.random() * (maxnumbers - 1)) + 1;
}
for (var i = numbercount; i >= 1; i--) {
for (var j = numbercount; j >= 1; j--) {
if ((i != j) && (r[i] == r[j])) ok = 0;
}
}
if (ok) {
var output = "";
for (var k = 1; k <= numbercount; k++) {
output += r[k] + ", ";
}
document.lotto.results.value = output;
} else numbers();
}
function userNumbers() {
var usersNumbers = new Array(5);
for (var count = 0; count <= 5; count++) {
usersNumbers[count] = window.prompt("Enter your number " + (count + 1) + ": ");
}
document.lotto.usersNumbers.value = usersNumbers;
}
Here is a lotto numbers generator and a scoring system. I'm going to leave it to you to validate the user input.
function lottoGen(){
var lottoNumbers = [];
for(var k = 0; k<6; k++){
var num = Math.floor(Math.random()*41);
if(lottoNumbers.indexOf(num) != -1){
lottoNumbers.push(num);
}
}
return lottoNumbers;
}
function scoreIt(){
var usersNumbers = document.getElementsByName('usersNumbers').item(0);
usersNumbers = String(usersNumbers)
usersNumbers = usersNumbers.split(' ');
var matches = 0;
for(var i = 0; i<6; i++){
if(lottoNumbers.indexOf(usersNumbers[i]) != -1){matches++;}
}
return matches;
}
Hi I'm new to this and trying to learn off my own back so obviously I'm no expert but the code above makes a lot of sense to me, apart from the fact I can't get it to work.. I tried to console.log where it says RETURN so I could see the numbers but it just shows an empty array still. I assumed this was to do with it being outside the loop..
I've tried various ways but the best I get is an array that loops the same number or an array with 6 numbers but some of which are repeated..
function lottoGen(){
var lottoNumbers = [];
for(var k = 0; k<6; k++){
var num = Math.floor(Math.random()*41);
if(lottoNumbers.indexOf(num) != -1){
lottoNumbers.push(num);
}
}
return lottoNumbers;
}
Lotto JS: CODEPEN DEMO >> HERE <<
(function(){
var btn = document.querySelector("button");
var output = document.querySelector("#result");
function getRandom(min, max){
return Math.round(Math.random() * (max - min) + min);
}
function showRandomNUmbers(){
var numbers = [],
random;
for(var i = 0; i < 6; i++){
random = getRandom(1, 49);
while(numbers.indexOf(random) !== -1){
console.log("upps (" + random + ") it is in already.");
random = getRandom(1, 49);
console.log("replaced with: (" + random + ").");
}
numbers.push(random);
}
output.value = numbers.join(", ");
}
btn.onclick = showRandomNUmbers;
})();