i want to create hollow square with function in javascript.
this my code
let test = num => {
var edge = '*';
var inside = ' ';
var printline;
for (var i = 1; i <= num; i++) {
if (i === 1 || i === num) {
printline = Array(num + 1).join(edge);
} else {
printline = edge + Array(num - 1).join(inside) + edge;
}
}
return printline;
}
console.log(test(4));
currently output is
****
but i want my output like this
****
* *
* *
****
You should reuse printline, not overwrite it.
Also, it needs the new line and carriage return (\r\n) on every iteration
let test = num => {
var edge = '*';
var inside = ' ';
var printline='';
for (var i = 1; i <= num; i++) {
if (i === 1 || i === num) {
printline += Array(num + 1).join(edge);
} else {
printline += edge + Array(num - 1).join(inside) + edge;
}
printline+='\r\n';
}
return printline;
}
console.log(test(4));
please update the lines of codes below.
var printline = '';
printline += Array(num + 1).join(edge) + '\n';
printline += edge + Array(num - 1).join(inside) + edge + '\n';
Related
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function init(){
var resArr = [];
for (var i = 0; i < 10; i++) {
var obj = new Object();
obj.q = getRandomInt(3,5);
obj.r = getRandomInt(1,10);
resArr.push(obj);
}
var str = '<table border=1><th>Multiplication</th>';
for (var i = 0; i < resArr.length; i++) {
str+='<tr><td>'+resArr[i].q+' * '+resArr[i].r+' = '+(resArr[i].q *resArr[i].r)+'</td></tr>';
}
str += '</table>';
document.getElementById('multiTable').innerHTML = str;
}
init();
<button type="button" name="button" onclick="init()">Refresh</button>
<div id='multiTable'></div>
Here I am generating random object and pushing to an array. I am really stuck how to check that created object is present or not in array.
I want to generate random number to show in multiplication table.
I created a function simply to check for duplicate objects in the array
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function checkDuplicate(arr, obj) {
for (var i = 0; i < arr.length; i++) {
if (arr[i].q == obj.q && arr[i].r == obj.r) {
return true;
break;
}
}
}
function init() {
var resArr = [];
for (var i = 0; i < 10; i++) {
var obj = new Object();
obj.q = getRandomInt(3, 5);
obj.r = getRandomInt(1, 10);
if (!checkDuplicate(resArr, obj)) {
resArr.push(obj);
}
else i--;
}
var str = '<table border=1><th>Multiplication</th>';
for (var i = 0; i < resArr.length; i++) {
str += '<tr><td>' + resArr[i].q + ' * ' + resArr[i].r + ' = ' + (resArr[i].q * resArr[i].r) + '</td></tr>';
}
str += '</table>';
document.getElementById('multiTable').innerHTML = str;
}
init();
<button type="button" name="button" onclick="init()">Refresh</button>
<div id='multiTable'></div>
You could use a hash table and insert all random combination into it after checking if already inserted.
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function init() {
var resArr = [],
hash = {};
for (var i = 0; i < 10; i++) {
var obj = new Object();
do {
obj.q = getRandomInt(3, 5);
obj.r = getRandomInt(1, 10);
} while (hash[[obj.q, obj.r].join('|')])
hash[[obj.q, obj.r].join('|')] = true;
resArr.push(obj);
}
var str = '<table border=1><th>Multiplication</th>';
for (var i = 0; i < resArr.length; i++) {
str += '<tr><td>' + resArr[i].q + ' * ' + resArr[i].r + ' = ' + (resArr[i].q * resArr[i].r) + '</td></tr>';
}
str += '</table>';
document.getElementById('multiTable').innerHTML = str;
}
init();
<button type="button" name="button" onclick="init()">Refresh</button>
<div id='multiTable'></div>
Try with Array#filter() method .check the matched object length .And change with while loop for always give a 10 result's
updated
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function init() {
var resArr = [];
var i=0;
while (true) {
var obj = new Object();
obj.q = getRandomInt(3, 5);
obj.r = getRandomInt(1, 10);
if(!resArr.filter(a=> a.q == obj.q && a.r == obj.r).length>0){
resArr.push(obj);
i++;
}
if(i == 10){
break;
}
}
var str = '<table border=1><th>Multiplication</th>';
for (var i = 0; i < resArr.length; i++) {
str += '<tr><td>' + resArr[i].q + ' * ' + resArr[i].r + ' = ' + (resArr[i].q * resArr[i].r) + '</td></tr>';
}
str += '</table>';
document.getElementById('multiTable').innerHTML = str;
}
init();
<button type="button" name="button" onclick="init()">Refresh</button>
<div id='multiTable'></div>
I am trying to add all values of class tmpcpa and place result in final_cpa but final_cpa always return 0.
document.getElementById('cpa' + arr[0]).innerHTML = cpa + '(' + '<label id="tmpcpa">' + tmp_cpa + "</label>" +' For Final' + ')';
var final_cpa = calculate_final_cpa();
console.log(final_cpa);
function calculate_final_cpa() {
var final_cpa = 0;
$('.tmpcpa').each(function () {
if ($(this).val() != 0)
final_cpa += parseInt($(this).text()) || 0;
});
return final_cpa;
}
Surprisingly when i view source code in browser HTML appears as
<label class="tmpcpa">0</label> but when i do inspect element it shows as
<label class="tmpcpa">30.0</label>
Update here is the whole JS. HTML calls process function which ultimately calls calculate_final_cpa()
//"use strict";
function process(arr) {
document.getElementById('txtgrade' + arr[0] + arr[1] + arr[2]).innerHTML = show_grade(document.getElementById('txtpercentage' + arr[0] + arr[1] + arr[2]).value);
if (validateForm(arr)) {
var module_percentage = +document.getElementById('txtpercentage' + arr[0] + arr[1] + arr[2]).value;
var module_credit = +document.getElementById('txtcredit' + arr[0] + arr[1] + arr[2]).innerHTML;
if (!isNaN(module_percentage) || !isNaN(module_credit)) {
module_percentage = 0;
module_credit = 0;
var total_credit_semester = 0;
var sum_module_percentage_x_credit = 0;
for ( i= 2 ; i <= arr[3] + 1 ; i++) {
module_percentage = +document.getElementById('txtpercentage' + arr[0] + arr[1] + i).value;
module_credit = +document.getElementById('txtcredit' + arr[0] + arr[1] + i).innerHTML;
sum_module_percentage_x_credit += module_percentage * module_credit;
total_credit_semester += module_credit;
}
//console.log(module_percentage);
var spa = sum_module_percentage_x_credit / total_credit_semester;
spa = spa.toFixed(1);
document.getElementById('spa' + arr[0] + arr[1]).innerHTML = spa;
calculate_cpa(arr);
}
}
}
function validateForm(arr) {
var isValid = true;
var tbl_id = 'tbl_semester' + arr[0] + arr[1];
$('#' + tbl_id + ' :input').each(function () {
if ($(this).val() === '')
isValid = false;
});
return isValid;
}
function calculate_final_cpa() {
var final_cpa = 0;
$('.tmpcpa').each(function () {
if ($(this).val() != 0)
final_cpa += parseInt($(this).text()) || 0;
});
return final_cpa;
}
/*
* Works for 2 semester per level and 3 year course (optimize later)
*/
function calculate_cpa(arr) {
var isValid = true;
for ( i= 1 ; i <= 2 ; i++) {
var spa = document.getElementById('spa' + arr[0] + i).innerHTML;
if (spa == "N/A") {
isValid = false;
}
}
if (isValid) {
var total_credit_level = 0;
var total_spa_x_credit = 0;
for ( i= 1 ; i <= 2 ; i++) {
var arr2= [arr[0], i];
var spa = +document.getElementById('spa' + arr[0] + i).innerHTML;
total_spa_x_credit += spa * getcredits(arr2);
total_credit_level += getcredits(arr2);
}
var cpa = total_spa_x_credit / total_credit_level;
cpa = cpa.toFixed(1);
document.getElementById('cpa' + arr[0]).innerHTML = cpa;
var level = +document.getElementById('level' + arr[0]).innerHTML
var tmp_cpa = ((level / 100) * cpa).toFixed(1);
document.getElementById('cpa' + arr[0]).innerHTML = cpa + '(' + '<label class="tmpcpa">' + tmp_cpa + "</label>" +' For Final' + ')';
var final_cpa = calculate_final_cpa();
console.log(final_cpa);
if (final_cpa != 0) {
var award = show_award(final_cpa);
document.getElementById('award').innerHTML = award;
document.getElementById('finalcpa').innerHTML = final_cpa;
}
}
}
function getcredits(arr) {
var sum = 0;
var tbl_id = 'tbl_semester' + arr[0] + arr[1];
$('#' + tbl_id + ' .sum').each(function () {
sum += parseInt($(this).text())||0;
});
return sum;
}
function show_grade(module_percentage) {
if (isNaN(module_percentage)) {
return 'N/A';
}
if (module_percentage >= 70 && module_percentage <= 100) {
return 'A';
} else if (module_percentage >= 60 && module_percentage < 70) {
return 'B';
} else if (module_percentage >= 50 && module_percentage < 60) {
return 'C';
} else if (module_percentage >= 40 && module_percentage < 50) {
return 'D';
} else {
return 'F';
}
}
function show_award(cpa) {
if (isNaN(cpa)) {
return 'N/A';
}
if (cpa >= 70 && cpa <= 100) {
return 'First Class with Honours';
} else if (cpa >= 60 && cpa < 70) {
return 'Second Class First Division with Honours';
} else if (cpa >= 50 && cpa < 60) {
return 'Second Class Second Division with Honours';
} else if (cpa >= 45 && cpa < 50) {
return 'Third Class with Honours';
} else if (cpa >= 40 && cpa < 45) {
return 'Pass';
} else if (cpa < 40) {
return 'No award';
}
}
you need to be sure you are calling the function after the document is ready.
Also, you are using unassigned value.
</body>
<script>
function calculate_final_cpa() {
var final_cpa = 0;
$('.tmpcpa').each(function () {
if ($(this).val() != 0)
final_cpa += parseInt($(this).text()) || 0;
});
return final_cpa;
}
$(document).ready(function(){
var final_cpa = calculate_final_cpa();
document.getElementById('cpa' + arr[0]).innerHTML = cpa + '(' + '<label id="tmpcpa">' + final_cpa + "</label>" +' For Final' + ')';
console.log(final_cpa);
});
</script>
I created a list of buttons from code behind, and append them on some div, how ever each button has an onclick java script function
here is how I did it:
string[] messages = CM.GetMessages(Session["USER_EMAIL"].ToString()).Split(new string[] { "$STARTCHAT$" }, StringSplitOptions.None);
string[] usersalone = CM.GetChaters(Session["USER_EMAIL"].ToString()).Split(new string[] { "$NEWUSER$" }, StringSplitOptions.None);
string[] username = CM.GetUserNames(Session["USER_EMAIL"].ToString()).Split(new string[] { "$NEWUSER$" }, StringSplitOptions.None);
for (int i = messages.Length-2; i>=0; i--)
{
Button b = new Button();
b.ID = Session["USER_EMAIL"].ToString()+username[i];
b.Text = "Chat With: " + usersalone[i] ;
b.Width = 250;
b.Height = 100;
b.OnClientClick = "return DisplayMessage('" + messages[i+1] + "','" + username[i] + "','" + Session["USER_EMAIL"].ToString() + "')";
b.Style.Add("background-color", "rgb(246, 246, 246)");
// lblChatwith.Text = username[i];
NewMsgNotArrow.Controls.Add(b);
}
and here is my java script function:
function DisplayMessage(messages, from, username) {
document.getElementById("AllMessages").innerText ="";
document.getElementById("DivDisplayMessage").style.visibility = "visible";
document.getElementById("lblChatwith").innerText = from;
var MessageForEachUser = messages.split("$SAMECHATNEWTEXT$");
for (var i = 0; i < MessageForEachUser.length; i++)
{
var ck = MessageForEachUser[i].indexOf("$" + from.toUpperCase() + "$") > -1;
if (ck == true) {
document.getElementById("AllMessages").innerText += from.toUpperCase() + ":\n";
var temp = MessageForEachUser[i].split("$" + from.toUpperCase() + "$");
MessageForEachUser[i] = temp[0];
}
if (ck == false) {
document.getElementById("AllMessages").innerText += username.toUpperCase() + ":\n";
var temp = MessageForEachUser[i].split("$" + username.toUpperCase() + "$");
MessageForEachUser[i] = temp[0];
}
document.getElementById("AllMessages").innerText += MessageForEachUser[i] + "\n______________________________________________________" + "\n";
}
return false;
}
every thing is working well but, when i want to use one of the labels like "lblchatwith" from code behind it return an empty string.
i have implemented this code to display xml in html using javascript
current output
Need something like
Here is my code
function parseXML(R, s) {
var C = R.childNodes;
var str = '';
for (var i = 0; i < C.length; i++) {
var n = C[i];
var f = false;
if (n.nodeType !== 3) {
str += '<br><<span class="nn">' + n.nodeName + '</span>>';
if (n.hasChildNodes()) {
f = true;
str += parseXML(n, s++);
}
str += '</<span class="nn">' + n.nodeName + '</span>>';
} else {
str += '<span class="nv">' + n.nodeValue + '</span>';
}
if (f) {
str += '<br>';
}
}
var str = str.replace(/(<br>)+/g, '<br>');
return str;
}
how i call this
R : xml object
s : initial 0 (i am passing this so that i can display xml as hirarchical view)
Output in second
- is not required
i have post second out as it can be seen while opening xml document in firefox
please ask if any doubt
I solved it myself.
Updated code with the solution
var pre = 0;
function parseXML(R, s) {
var C = R.childNodes;
var str = '';
for (var i = 0; i < C.length; i++) {
var n = C[i];
if (n.nodeType !== 3) {
str += '<br>' + gs(s) + '<b><</b><span class="nn">' + n.nodeName + '</span><b>></b>';
if (n.hasChildNodes()) {
str += parseXML(n, s + 1);
}
if (pre !== 3) {
str += '<br>' + gs(s);
}
str += '<b><</b>/<span class="nn">' + n.nodeName + '</span><b>></b>';
} else {
str += '<span class="nv">' + n.nodeValue + '</span>';
}
pre = n.nodeType;
}
return str;
}
I'm using a server-side JS for a counter:
var date = new Date(2013,1,01);
var now = new Date();
var number = 0;
var increment = 3290;
var second = 1;
var secondTotal = (now.getTime()-date.getTime())/1000;
var incrementTotal = (secondTotal/1)*3290;
number = Math.round(number+incrementTotal);
function init() {
document.getElementById("kwh_fam_an").innerHTML = number;
setInterval('incrementation()',second*1000);
}
function incrementation() {
number = number+increment;
document.getElementById("kwh_fam_an").innerHTML = number;
}
I'm trying to change the format by forcing a colon and a space every 3 figures but the code below doesn't work:
function lisibilite_nombre(nbr) {
var number = '' + nbr;
var retour = '';
var count = 0;
for (var i = number.length - 1; i >= 0 ; i--) {
if (count != 0 && count % 3 == 0)
retour = number[i] + ' ' + retour ;
else
retour = number[i] + retour ;
count++;
}
alert('nb : ' + nbr + ' => ' + retour);
return retour;
}
Do you have any idea ?
You're adding the space but not the colon. Change:
retour = number[i] + ' ' + retour ;
to:
retour = number[i] + ': ' + retour;