Need for/while/do while loops to repeat asterisks - javascript

I have this problem, to repeat 30 asterisks for 3 lines. I made this example code but it repeats 30 numbers (1..30) from 1 number for first line, up to 30 numbers for the last line. So, I'd need the code to repeat 30 asterisks, for 3 lines each but not quite like within this code.
Sorry for bad elaboration.
var text = "";
var max = 30;
for(i = 0; i < max; i++)
{
for(j = 0; j <= i; j++)
{
text += (j+1)+" ";
}
text += "<br />";
}

A more re-usable solution will be to make a generic repeatString function that simply makes multiple copies of any string.
function repeatString(s, times) {
for (var i = 0, r = ''; i < times; i++) {
r += s;
}
return r;
}
var line = repeatString('*', 30) + '<br />',
content = repeatString(line, 3);
http://jsfiddle.net/611y2vmz/1/

Repeat the loop three times, like this:
for ( var i = 0; i < 3; i++ ) { // this is the line loop
for ( var j = 0; j < 30; j++ ) { //this is the asterix loop
document.write('*');
}
document.write('<br>');
}
Here's a simple demo

If you are using ES2015 (ES6) syntax you can leverage repeat function and string templating. Using those features your code will look like this
let text = (`${'*'.repeat(30)}<br/>`).repeat(3);
Here is an example of ES2015 (ES6) code
if you are using ES5 then you can do this way:
String.prototype.repeat = function(count) {
return count < 1 ? '' : new Array(count + 1).join(this);
};
var text = ('*'.repeat(30) + '<br/>').repeat(3);
Here is an example of ES5 code

You need your outer loop to iterate 3 times, and your inner loop to iterate 30 times. Each iteration of your inner loop should add an asterisk (instead of adding j+1 like you are doing now). This will produce 3 rows of 30 asterisks.

var TEXT = "*";
var LINE_SEPARATOR = "<br/>";
var TEXT_COUNT = 30;
var LINE_COUNT = 3;
var output = "";
for (line = 1; line <= LINE_COUNT; ++line) {
for (text = 1; text <= TEXT_COUNT; ++text) {
output += TEXT;
}
output += LINE_SEPARATOR;
}
document.write(output);

An alternative would be to use recursion:
function stars(num) {
return num > 0 ? stars(num - 1) + '*' : '';
}
var content = stars(30) + '<br/>' + stars(30) + '<br/>' + stars(30);
DEMO

Related

JavaScript to remove string in OBX 5.1 starting with first occurance of "\\." till the end

I am trying to write a JavaScript to remove string in OBX 5.1 after "\."
Here is the inbound OBX segment:
OBX|2|NM|WBC^White Blood Cell Count^WinPath||3.2\\.br\\This result could indicate your patient might have\\.br\\sepsis. Take into consideration the absolute\\.br\\neutrophil and lymphocyte counts when making your|x 10^9/l|4 - 10|L|||F|||||
Here is the expected outbound OBX segment:
OBX|2|NM|WBC^White Blood Cell Count^WinPath||3.2|x 10^9/l|4 - 10|L|||F|||||
I have written this Javascript code. It is compiling but not removing the unwanted text.
Here is what I have written:
var RegExp_pattern = "\\.";
function indexOf(stringToTrim) {
return stringToTrim.indexOf(RegExp_pattern);
}
function substring(ssstringToTrim) {
return ssstringToTrim.substring(indexOf(OBX_TestValue), -1);
}
/* Single input message case */
var next = output.append(input[0]);
// loop through Order Group (OBR) & Result Group (OBX)
//
var cntObs = next.getRepeatCount("ObservationMessage");
for (var i = 0; i < cntObs; i++) {
var cntOrders = next.getRepeatCount("ObservationMessage[" + i + "]/Order");
for (var j = 0; j < cntOrders; j++) {
var cntResults = next.getRepeatCount("ObservationMessage[" + i + "]/Order[" + j + "]/Results");
for (var k = 0; k < cntResults; k++) {
var OBX_TestValue = next.getField("ObservationMessage[" + i + "]/Order[" + j + "]/Results[" + k + "]/OBX/ObservationValue");
if (OBX_TestValue.indexOf(OBX_TestValue) > 0) {
OBX_TestValue = substring(OBX_TestValue);
}
}
}
}
To remove everything from the first occurance of "\." until the end of the string you should use a regular expression.
var str = "OBX|2|NM|WBC^White Blood Cell Count^WinPath||3.2\\.br\\This result could indicate your patient might have\\.br\\sepsis. Take into consideration the absolute\\.br\\neutrophil and lymphocyte counts when making your|x 10^9/l|4 - 10|L|||F|||||";
var mtch = str.replace(/\\\..*/, '');
console.log(mtch);

Javascript Fib series test case fails

I am trying to complete this assignment for the Javascript Fibonacci series. The logic works for input 5 and 6. But the test case for 8 fails.
function fibonacciSequence(input) {
//Type your code here.
var i = 0;
var fib = [];
fib[0] = 0;
fib[1] = 1;
var out ="0"+ "" +"1";
for (i = 2; i <=input; i++) {
fib[i] = fib[i-2] + fib[i-1];
out = out+ ""+ fib[i];
console.log("i is" + i + " out is" + out);
}
return out;
}
I cannot figure out what is going wrong..
It seems like things are just getting messed up with how you are adding the items to the string. Since there is no space between out + "" + fib[i], I think that would be messing with the formatting. Once i had spaces it seems to work fine, a double digit number wouldnt mess with a string like that.
function fibonacciSequence(input) {
var fib = [];
fib[0] = 0;
fib[1] = 1;
let out = ""
out+= ` ${0} `
out+= `${1}`
for (let i=2; i <=input; i++) {
fib[i] = fib[i-2] + fib[i-1];
out+= ` ${fib[i]}`
}
return out;
}
You are comparing the input (which it seems like this is maybe the number you want to stop at) to i which (plus or minus a bit) is the number of numbers in the list. You probably want to be comparing fib[i], or something like it to input to decide whether to terminate the loop.
Edit: If that's wrong and you do want input to be the number of numbers in the list, then you could just join fib at the end:
function fibonacciSequence(input) {
//Type your code here.
var i = 0;
var fib = [];
fib[0] = 0;
fib[1] = 1;
//var out ="0"+ "" +"1";
for (i = 2; i <=input; i++) {
fib[i] = fib[i-2] + fib[i-1];
//out = out+ ""+ fib[i];
//console.log("i is" + i + " out is" + out);
}
return fib.join(' ');
}
for(let j = 0; j < 9; j++)
console.log('input: ' + j + ' :: ', fibonacciSequence(j));
Unless ... I've got the wrong end of the stick and #Grant Herman's answer already does what you want?

Javascript syntax issue in code

Can someone tell me why this bit of JavaScript is buggy?
I have HTML also, but I don't want to make this a massive code dump.
<script type = 'text/javascript'>
var playerCards = [];
var dealerCards = [];
function deal() {
var newCard = Math.random() % 12;
var newCard2 = Math.random() % 12;
playerCards += newCard;
playerCards += newCard2;
var counter = 0;
for (var i = 0; i < playerCards.length; ++i) {
counter += i;
}
document.getElementById("playerTotal").innerHTML = counter;
var dCounter = 0;
for (var j = 0; j < playerCards.length; ++j) {
dCounter += j;
}
document.getElementById("dealerTotal").innerHTML = dCounter;
}
</script>
I'm gonna assume this is a silly syntax error someplace, but I can't find it.
I'm guessing that this isn't doing what you expect it to:
playerCards += newCard;
playerCards += newCard2;
Try this instead:
playerCards.push(newCard);
playerCards.push(newCard2);
The first snippet is trying to "add" a number to an array, which doesn't exactly make sense. Through some arcane JavaScript rules, this turns the result into a string.
I'm guessing that you want to concatenate to an array instead.
Math.random returns a number between 0 and 1 - so Math.random() % 12 will probably be zero
var playerCards = [];
playerCards += newCard; //
what are you even trying to do there?
var counter = 0;
for (var i = 0; i < playerCards.length; ++i) {
counter += i;
}
if playerCards had a length, this loop would result in counter having value of 0, 1, 3, 6, 10 .. n(n+1) / 2 - probably not what you intended, but who knows

Javascript: using a for statement as a variable

I'm fairly new to javascript and something I've been playing with lately is the 'for' statement. I'm questioning one thing, though. I've learned how to make a 'for' statement do things as if it was an output, like this:
for (i = 0; i < 3; i++) {
console.log(i);
}
But what if you want to set a variable for the whole output of the 'for' statement?
var destinationArray = ["town", "areas", "bosses"];
var destinationArraySet = 1;
var i;
for ( i = 0; i < destinationArraySet; i++) {
console.log(destinationArray[i]);
} /*the whole thing should be equal to var destination */
var userDestinationPrompt = ("Where would you like to go? Available places: " +
/* var destination */
+
".").toUpperCase();
To give some more context: I'm making a game that allows further destinations when the destination before is cleared. Once that's achieved, I set destinationArraySet to a higher value, which means that more places would be logged and put after 'Available places'.
Help would be very appreciated! If there's something not clear enough let me know.
The for statement is not an expression, so it doesn't have a return value. Use a variable to collect values in the loop:
var destination = '';
for (var i = 0; i < destinationArraySet; i++) {
destination += destinationArray[i] + ' ';
}
Of course, if you only want to concatenate the values in part of an array, you can use the slice method to get part of it, then the join method:
var destination = destinationArray.slice(0, destinationArraySet).join(' ');
var destination = '';
var destinationArray = ["town", "areas", "bosses"];
var destinationArraySet = 1;
for (var i = 0; i < destinationArraySet; i++) {
destination += destinationArray[i] + '\n';
}
console.log(destination);
Try this -
var destinationArray = ["town", "areas", "bosses"];
var destinationArraySet = 1;
var i;
var availablePlaces = '';
var separator = '';
for ( i = 0; i < destinationArraySet; i++) {
availablePlaces += separator + destinationArray[i];
separator = ', ';
}
var userDestinationPrompt = ("Where would you like to go? Available places: " +
availablePlaces + ".").toUpperCase();
The for statement doesn't have an "output", it's not a function. Thinking for as a function will give you troubles later on. for is simply a statement that continuously execute the block of code inside. It does not "output", or in other words, return any value.
Do this instead:
var destinationArray = ["town", "areas", "bosses"], destinationArraySet = 1;
var userDestinationPrompt = ("Where would you like to go? Available places: " +
destinationArray.slice(0, destinationArraySet).join("\n")
+ ".").toUpperCase();
prompt(userDestinationPrompt);
Demo: http://jsfiddle.net/7c2b9q7m/1/
destinationArray.slice(0, destinationArraySet): Cuts the array to the specified length.
.join("\n"): Join the newly created array by \ns (newline) to micic the default console.log behavior.

Need help w/ JavaScript and creating an html table from array

I've tried everything I can find via google and nothing has worked correctly. Output is just a single row with all the contents of the array listed. What I need is a way to write the contents of an array but after 3 cells, automatically start a new line. I'll post the code I've made below as well as the question. (yes this is from an assignment. :( )
//***(8) place the words in the string "tx_val" in a table with a one pixel border,
//*** with a gray backgound. Use only three cells per row. Empty cells should contain
//*** the word "null". Show the table in the span block with id="ans8"
var count = i % 3;
var nrow = "";
var out = "<table border='1' bgcolor='gray'><tr>"
for (var i=0; i<txArr.length; i++)
{
out += ("<td>" + txArr[i] + "</td>");
count++;
if (count % 3 == 0)
{
nrow += "</tr><tr>";
}
}
document.getElementById('ans8').innerHTML = out + nrow;
you need to print the tr's inside the table (annd add a </table>!):
var count = i % 3; // btw. what's this??
var nrow = "";
var out = "<table border='1' bgcolor='gray'><tr>"
for (var i=0; i<txArr.length; i++)
{
out += "<td>" + txArr[i] + "</td>";
count++;
if (count % 3 == 0)
out += "</tr><tr>";
}
out += "</table>";
document.getElementById('ans8').innerHTML = out;
Rather than try to write out the html, try manipulating the dom. It seems much more straightforward to me. Take a look at the following:
var row = table.insertRow();
msdn
mdc
var cell = row.insertCell();
msdn
mdc
var cellContent = document.createTextNode(txArr[i]);
msdn
mdc
cell.appendChild(cellContent);
msdn
mdc
For deciding when to start a new row, just use the modulus operator (%
msdn
mdc
) against i:
if (i % 3 == 0)
{
row = table.insertRow()
}
You'd end up with something like this:
var container = document.getElementById("ans8");
var t = container.appendChild(document.createElement("table"));
var row;
txArr.forEach(function (item, i)
{
if (i % 3 == 0)
{
row = t.insertRow()
}
row.insertCell().appendChild(document.createTextNode(item));
});
I'll leave a little for you to figure out - border, background color, getting the word "null" in there. It is your homework after all. :-)
Also, for older browsers you'll need to add Array.forEach in yourself.
I prefer using an array over concatination
var html = [];
html.push("<table><tr>");
var i = 0;
for (var k in txArr)
{
if(i>=3){
i=0;
html.push("</tr><tr>");
}
html.push("<td>" + txArr[k] + "</td>");
i++;
}
html.push("</tr></table>");
document.getElementById('ans8').innerHTML = html.join('');
// wrapped in function
function arrayToTable(a,cols){
var html = [];
html.push("<table><tr>");
var i = 0;
for (var k in a)
{
if(i>=cols){
i=0;
html.push("</tr><tr>");
}
html.push("<td>" + a[k] + "</td>");
i++;
}
html.push("</tr></table>");
return html.join('')
}
document.getElementById('ans8').innerHTML = arrayToTable(txArr, 3);
It might be a tad easier to accomplish with something like
buffer = "<table>";
for(var r = 0; r < 10; r++){
buffer += "<tr>";
for(var c = 0; c < 3 ; c++){
buffer += "<td>Cell: " + r + ":" + c + "</td>";
}
buffer += "</tr>";
}
buffer += "</table>";
document.getElementById("ans8").innerHTML = buffer;
That would create a table 30 rows long by 3 columns for each row.
you might be assigning values to "count" too early as you don't know what i is yet. and you are not spitting out the value of nrow anywhere... change it to out.
var count;
var nrow = "";
var out = "<table border='1' bgcolor='gray'><tr>"
for (var i=0; i<txArr.length; i++)
{
out += ("<td>" + txArr[i] + "</td>");
count++;
if (count % 3 == 0)
{
out += "</tr><tr>";
}
}
document.getElementById('ans8').innerHTML = out + nrow;
Basically I would split it up into 3 functions, for readability and maintenance. These functions would consist of creating a cell, a row, and a table. This definitely simplifies reading the code. As I have not tested it, below is an example of what I would do.
function createTableCell(value) {
return value == null? "<td>NULL</td>":"<td>" + value + "</td>";
}
function createTableRow(array) {
var returnValue = "";
for (var i = 0; i < array.length; i++) {
returnValue = returnValue + createTableCell(array[i]);
}
return "<tr>" + returnValue + "</tr>";
}
function arrayToTable(array, newRowAfterNArrayElements) {
var returnValue = "<table>";
for (var i = 0; i < array.length; i = i + newRowAfterNArrayElements) {
returnValue = returnValue + createTableRow(array.split(i, (i + newRowAfterNArrayElements) - 1));
}
return returnValue + "</table>";
}
document.getElementById("ans8").innerHTML = arrayToTable(txArr, 3);
In addition this makes your code much more dynamic and reusable. Suppose you have an array you want to split at every 4 element. Instead of hardcoding that you can simply pass a different argument.
Here's a live example of doing this with DOMBuilder, and of using the same code to generate DOM Elements and an HTML String.
http://jsfiddle.net/insin/hntxW/
Code:
var dom = DOMBuilder.elementFunctions;
function arrayToTable(a, cols) {
var rows = [];
for (var i = 0, l = a.length; i < l; i += cols) {
rows.push(a.slice(i, i + cols));
}
return dom.TABLE({border: 1, bgcolor: 'gray'},
dom.TBODY(
dom.TR.map(rows, function(cells) {
return dom.TD.map(cells);
})
)
);
}
var data = [1, 2, null, 3, null, 4, null, 5, 6];
document.body.appendChild(arrayToTable(data, 3));
document.body.appendChild(
dom.TEXTAREA({cols: 60, rows: 6},
DOMBuilder.withMode("HTML", function() {
return ""+arrayToTable(data, 3);
})
)
);
Yes, you can build from scratch...but there's a faster way. Throw a grid at it. The grid will take data in a string, array, json output, etc and turn it into a proper HTML outputted table and will allow you to extend it with sorting, paging, filtering, etc.
My personal favorite is DataTables, but there are numerous others out there.
Once you get proficient, setting one of these up literally takes 5 minutes. Save your brain power to cure world hunger, code the next facebook, etc....

Categories

Resources