JavaScript: Is there any way to print outputs without newline? - javascript

I am learning JavaScript and I am trying to print this particular sequence of hashes:
#
##
###
I wrote this piece of code to produce the sequence:
for(let i = 0; i < 3; i++){
for(let j = 0; j <= i; j++){
print('#');
}
print('\n');
}
Note: I am using rhino to execute the program on my Ubuntu terminal.
rhino <filename>.js //Command used to execute JavaScript file.
The output I obtain:
#
#
#
#
#
#
I obtain the correct output with this program:
var starString = "";
for(let i = 0; i < 3; i++){
for(let j = 0; j <= i; j++){
starString += '#';
}
print(starString);
starString = "";
}
My question is this: Is there a print statement which I can use that does not add a newline at the end of the statement?

No, not directly using print(). However you can make your own function using System.out.print() that prints without the new lines:
function printNOn(arg) {
java.lang.System.out.print(arg)
}
result:
MBP:rhino1_7R4 mark$ java -jar js.jar
Rhino 1.7 release 4 2012 06 18
js> function printNOn(arg) {
java.lang.System.out.print(arg)
}
js> for(let i = 0; i < 3; i++){
> for(let j = 0; j <= i; j++){
> printNOn("#")
> }
> printNOn('\n')
> }
#
##
###
js>

console.log('Node js - hello world');
for(var counter = 0; counter< 5 ;counter++){
// console.log("----------------");
var pound = "#";
for(var localcounter = 0; localcounter < counter; localcounter++ ){
//console.log("localcounter is ", localcounter);
//console.log("counter is ", counter);
//console.log(pound);
pound += "#";
//console.log(pound);
}
console.log(pound);
//console.log("----------------");
//
pound = "";
pound = null;
}

Related

How do I print on a new line after every 6th number?

So I'm making a loop that's supposed to print from 0-99 and it's supposed to make a new line after every 6th number like in the example below;
012345
678910
But right now it doesn't make a new line it just increases space between the "chunks" it's displaying. How do I get it to make a new line after every 6th number?
for (var i = 0; i < 100; i++) {
for (var j = 0; j < 6 && i <= 100; j++) {
document.body.innerHTML += i;
i++;
}
document.body.innerHTML += '\n';
i--;
}
A literal newline doesn't result in a visual newline in HTML:
foo
bar
You need <br> instead:
for (var i = 0; i < 100; i++) {
for (var j = 0; j < 6 && i <= 100; j++) {
document.body.innerHTML += i;
i++;
}
document.body.innerHTML += '<br>';
i--;
}
Or, I'd prefer to surround each block in a <div> - and you can increment the i only inside the inner loop to make the logic clearer:
for (var i = 0; i < 100;) {
const div = document.body.appendChild(document.createElement('div'));
for (var j = 0; j < 6 && i <= 100; j++, i++) {
div.textContent += i;
}
}
You could use a modulus to insert a br every sixth item - save you doing loops inside loops:
for (var i = 0; i < 100; i++) {
document.body.innerHTML += i;
if ((i + 1) % 6 === 0) { // using i plus one as you start at 0
document.body.innerHTML += '<br>';
}
}
I am answering
supposed to print from 0-99 and supposed to make a new line after every 6th number
We need a PRE to not use a <br>
document.getElementById("res").innerHTML =
Array.from(Array(100).keys())
.map(i => `${i.toString().padStart(3," ")}${(i + 1) % 6 === 0 ? '\n' : ''}`)
.join("");
<pre id="res"></pre>

How to print a half pyramid in javascript

The code works but I don't want the inner for loop to take me to the new line.
for (i = 0; i < 5; i++) {
for (j = 1; j <= i; j++) {
console.log('*');
}
console.log();
}
console.log('-----------------');
console.log will automatically break the line. Concatenate to a string instead of a log. Log at the end.
let str = '';
for(i = 0; i <= 5 ; i++) {
for(j = 1; j <= i; j++) {
str += '*';
}
str += '\n';
}
console.log(str);
You can do this way, with the help of a string variable:
for (i = 0; i < 5; i++) {
var str = '';
for (j = 1; j <= i; j++) {
str+='*';
}
console.log(str);
}
console.log('-----------------');
If you want to print at the page, use like below
for (i = 0; i < 5; i++) {
let j=0;
do{document.write("*");j++;}while(j < i)
document.write("<br/>")
}
You need to break the line with the console.log you can also controle the space between * with output+='*' + " ";
function pyramid() {
var total = 5;
var output="";
for (var i = 1; i <= total; i++) {
for (var j = 1; j <= i; j++) {
output+='*' + " ";
}
console.log(output);
output="";
}
}
pyramid()
You can get rid of second for loop as follows:
var str = '';
for (i = 1; i <= 5; i++) {
str +=Array(i).join("*");
str +='\n';
}
console.log(str);
let string = "";
for (let i = 0; i < 5; i++){
string += '*';
console.log(string);
}
Output:
*
**
***
****
*****
A simple way to solve this "exercise" in JavaScript:
let width = ""
while(width.length < 6) console.log(width += `#` );
Basically, we create a string (width) and increment its value using the while loop till we hit a restriction.
I found the more typical method "bulky"(?)...plus there's the issue of not getting the exact picture of a half pyramid.
let i,j
for (i= 0; i < 6; i++){
for (j = 0; j<=i; j++){
console.log("#")
}
console.log("\n")
}
function pyramid(n){
let result = "";
for(let i=0; i<=n; i++){
result += "*".repeat(i);
result += "\n"
}
return result;
}
console.log(pyramid(5));
//OutPut
*
**
***
****
*****
As we need n number of pyramid structure with '' / '#' / any symbol. by using above code we can achieve. Here you can see we just created a function called pyramid with one parameter 'n'. and inside function we declare a variable 'result'. So inside for loop the length of 'i' is "<=n" and also you can use "repeat() method to print '' 'i' times. So if you call that function like console.log(pyramid(5)); You can able to see your Answer as expected..
shortest code:
console.log('*\n**\n***\n****\n*****');

Simple Javascript Christmas Tree

I created a half of the Christmas Tree but here I got blocked. Some one please help me to understand how to do the left side too.
for (var i = 0; i < 8; i++) {
for (var j = 0; j <= i; j++) {
document.write("^");
}
document.write("<br>");
}
<pre>
<script>
//Reads number of rows to be printed
var n = 8;
for(i=1; i<=n; i++)
{
//Prints trailing spaces
for(j=i; j<n; j++)
{
document.write(" ");
}
//Prints the pyramid pattern
for(j=1; j<=(2*i-1); j++)
{
document.write("*");
}
document.write("<br>");
}
</script>
</pre>
Source: http://codeforwin.org/2015/07/equilateral-triangle-star-pattern-program-in-c.html
C to JavaScript by me.
I wrote the following code for this problem.
I also added a nice extra, christmas-tree ornaments :-)
import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone
{
private static Random RND = new Random(System.currentTimeMillis()); // useful for placing balls
private static char[] BALLS = {'o','⌾','⛣','⏣','◍'}; // symbols being used as balls
public static void main (String[] args) throws java.lang.Exception
{
int w = 27; // width of the tree
int b = 10; // number of balls in the tree
String tree = ""; // this will end up containing the tree
// build tree
w = ( w % 2 == 1 ) ? w : 13; // check whether width is odd
for(int i=1;i<=w;i+=2){
int s = (w - i) / 2;
tree += repeat(' ', s) + repeat('*', i) + repeat(' ', s) + "\n";
}
// randomly replace some parts by balls
int i=0;
while(i < b){
int j = RND.nextInt(tree.length());
if(tree.charAt(j) == '*'){
tree = tree.substring(0, j) + BALLS[RND.nextInt(BALLS.length)] + tree.substring(j+1);
i++;
}
}
// build trunk
tree += repeat(' ', (w - 4) / 2) + repeat('*', 4) + "\n" + repeat(' ', (w - 4) / 2) + repeat('*', 4);
// output
System.out.println(tree);
}
// this function builds a String by repeating a given character a couple of times
private static String repeat(char c, int l){
String s = "";
for(int i=0;i<l;i++)
s += c;
return s;
}
}
The output should look something like this:
⏣
***
*o***
**⌾*o**
*****⛣**⛣
*****⌾****⏣
**◍*◍********
****
****
The keyword is think.
var x = 8;
for (let i = 0; i < x; i++) {
for (let j=x-1; j>i; j--) {
document.write("&nbsp&nbsp");
}
for (let k=0; k<=(i*2); k++) {
document.write("^");
}
document.write("<br>");
}
for (let i=0; i<2; i++) {
for (let j=0; j<(x*2)-3; j++) {
document.write("&nbsp");
}
document.write("^<br>");
}
Constraints: Only looks good starting from x = 5.
Original code by me
The answers above heavily rely on nested loops, thought I post another approach with "modern" JS (of course still using a single loop with the map function given to Array.from()):
function xmas(height) {
// add 1 more level for the trunk, e.g. height+1
return Array.from({length: height+1}, (v, i) => {
return i === height
// that's for the trunk of the tree
? '*'.padStart(Math.round((2 * i)/2), ' ')
// the actual tree "levels"
: '*'.repeat(2 * i + 1).padStart(2 * i + height-i, ' ');
}).join('\n');
}
document.write(`<pre>${xmas(10)}</pre>`);
maybe the attempt to make it work with .padStart() is not optimal because the math gets a bit ugly, but anyways, just for fun =)...
Here's a solution with a simple for loop without any nested loop.
let row = ""
let l = 9
for (let i = 0; i < l; i++) {
row += " ".repeat(l - i) + "*" + "*".repeat(i * 2) + `\n`;
}
console.log(row);
Simple christmas tree function:
function christmasTree(x) {
if(x < 3) {
return "";
}
let tree = "";
for(let i = 1; i <= x; i++) {
for(let j = 1; j <= x + x - 1; j++) {
if(j <= x - i || j >= x + i) {
tree += " ";
} else {
tree += "*";
}
}
tree += "\n";
}
return tree;
}
Incase you are looking for how to do this in a function for javascript or typescript
Use 3 for loops,
1 - Number of rows
2 - Number of spaces
3 - Number of characters
function christmas(n) {
let tree = '';
for (let i = 1; i <= n; i++) {
for (let j=0; j <= n-i; j++) {
tree += ' ';
}
for (k = 0; k< (i*2)-1; k++) {
tree += '*';
}
tree += '\n';
}
return tree;
}
console.log(christmas(3));
<pre>
<script>
//Reads number of rows to be printed
var n = 8;
for(i=1; i<=n; i++)
{
//Prints trailing spaces
for(j=i; j<n; j++)
{
document.write(" ");
}
//Prints the pyramid pattern
for(j=1; j<=(2*i-1); j++)
{
document.write("*");
}
document.write("<br>");
}
</script>
</pre>

Why is my eloquent javascript solution crashing?

I am trying to solve the last problem from chapter 2 of Eloquent JavaScript. It is at the very bottom of this page: http://eloquentjavascript.net/02_program_structure.html
(I tried copy pasting but the hashtag symbols keep messing up the formatting).
This is my code that crashes. It seems like it's stuck in an infinite loop or something but I can't see why!
var grid = "";
var bool = true;
var size = 8;
for(var i = 0; i < size; i++) {
if(bool = true) {
for(var i = 0; i < (size/2); i++) {
grid += " #";
}
grid += "\n";
bool = false;
}
else {
for(var i = 0; i < (size/2); i++) {
grid += "# ";
}
grid += "\n";
bool = true;
}
}
console.log(grid);
You're using the assignment operator = instead of comparator ( == or ===) . I.d probably change the name of the variable inside the second cycle for.. It may mess up with the one from the outer for cycle
Two problems:
if(bool = true) should be if(bool == true) (causing the infinite loop)
for(var i = 0; i < (size/2); i++) should be for(var j = 0; j < (size/2); j++) (i is already used in the outer loop)
Suggestions:
Change bool to something like odd_row
If you want to check if a boolean variable is true, you don't need the comparison: if(variable) also works
Try this: https://jsfiddle.net/t3rxx9dk/
var grid = "";
var bool = true;
var size = 8;
for(var i = 0; i < size; i++) {
if(bool == true) {
for(var j = 0; j < (size/2); j++) {
grid += " #";
}
grid += "\n";
bool = false;
}
else {
for(var j = 0; j < (size/2); j++) {
grid += "# ";
}
grid += "\n";
bool = true;
}
}
console.log(grid)
You should use another name for your iterator, you always use "i", that might cause issues
basic issues with your code
var grid = "";
var bool = true;
var size = 8;
for(var i = 0; i < size; i++) {
if(bool = true) {
// ^ -- trouble
for(var i = 0; i < (size/2); i++) {
// ^ another piece of trouble
grid += " #";
}
grid += "\n";
bool = false;
}
else {
for(var i = 0; i < (size/2); i++) {
grid += "# ";
}
grid += "\n";
bool = true;
}
}
console.log(grid);
on a better way to organize the code
var grid = ""
var shiftLine = false;
var size = 8;
for(var i = 0; i < size; i++) {
for(var k = 0; k < (size >> 1); k++) {
grid += shiftLine? " #" : "# ";
}
shiftLine = !shiftLine;
grid += "\n";
}
outputs
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
an exercise
As an exercise for you to review... Here is a way to do this in javascript in a way that takes advantage of Arrays and Strings and demonstrates a few different concepts of functional programming.
var size = 8;
var grid =
Array(size)
.join(
Array((size>>1)+1) // START HERE: create empty array of 1+ size/2
// because we want to delimit it '# ' to get
// size/2 '#'s
.join('# ') // join its elements using "# "
// this gives you a string "# # # # "
.trim() + '\n' // trim off last space and add newline
) // join these lines into an array of size (see Array(size) above)
.trim() // trim off the empty element at the end (due to last new-line)
.split('\n') // split it up into array elements because we need to shift every second line
.map(function(element, index, array) { // for each element (a line of # # # #)
if(index % 2 === 0) // if its index is even
return " " + element; // tack on a leading space
else // otherwise
return element; // leave it alone
})
.join('\n'); // now join everything with a new line
console.log(grid);

Finding every possible "non-duplicate" combination given a set of 6 digits

So I was first asked to create a function to find ever possible combination given a set of 6 numbers that can range from 0-9 EDIT Keep in mind that the user is given a prompt for the input so the input can change or be different.. so in other words the input would be 123456 or 099384 END EDIT. This function would have to return every possible combination for a result of 3 digits while using the inputted 6 digits a repeatable amount of times.. So it would return like 111 112 113 etc..
. I'm a php/javascript user and opted for javascript so that it can be run in the browser on a offline file.
This is what I've built below which works well.
function findthree(nums) {
for (var i = 0; i < 10; i++) {
if (in_array(i, nums)) {
for (var ii = 0; ii < 10; ii++) {
if (in_array(ii, nums)) {
for (var iii = 0; iii < 10; iii++) {
if (in_array(iii, nums)) {
$('body').append('<div>' + i + '' + ii + '' + iii + '</div>');
}
}
}
}
}
}
}
function in_array(needle, haystack) {
var length = haystack.length;
for (var i = 0; i < length; i++) {
if (haystack[i] == needle) return true;
}
return false;
}
My Question Is.. How would I create a similar function that shows every combination EXCEPT "combination duplicates". In other words, the function will not return 211 because 112 was already returned and 654 will not be returned because 456 would of already been returned. I was going to attempt to use a array_difference function but can not figure it out completely how that would work.
Thank you in advance for any help.
EDIT Answer found with help of the answer I selected
function findthreenodupe(nums) {
nums = $.distinct(nums);
nums.sort(function(a, b) {
return a - b
});
alert(nums);
for (var i = 1; i < 10; i++) {
if (in_array(i, nums)) {
for (var ii = i; ii < 10; ii++) {
if (in_array(ii, nums)) {
for (var iii = ii; iii < 10; iii++) {
if (in_array(iii, nums)) {
$('body').append('<div>' + i + '' + ii + '' + iii + '</div>');
}
} // end of iii for loop
} // end of ii for loop
} // end of i for loop
}
}
}
The first thing you want to do is sort your input and remove duplicate digits. For example, from 099384 you get 03489.
Then, you don't even have to check all the digits from 0-9, and you can work directly with the array index. That will eliminate some work, and you can get rid of the ugly if(in_array(i, nums)) brackets. Something like this should work:
for(var i=0; i<nums.length; i++){
for(var ii=i; ii< nums.length; ii++){
for(var iii=ii; iii<nums.length; iii++){
$('body').append('<div>' + nums[i] + '' + nums[ii] + '' + nums[iii] + '</div>');
}
}
}
The key difference is not starting with the first index each time, but with the previous digit. This ensures each digit is >= to the one before it(since it's sorted), and it ends up resembling the handshake problem.
For the sample input above(revised to 03489), you can visualize what it's doing below. Each run of the iii loop is a number. Each line is ii loop run, and each "block" is a run of the outer i loop.
000 003 004 008 009
033 034 038 039
044 048 049
088 089
099
333 334 338 339
344 348 349
388 389
399
444 448 449
488 489
499
888 889
899
999
Bonus: The number of combinations you'll find this way will always be the tetrahedral number for the number of distinct digits in nums.
Following code would display the combination for 4,5,6. You can change to include what ever value
for (var i = 4; i < 7; i++)
for(var y = i; y < 7 ; y++)
for(var z = y ; z < 7; z++)
$('#result').append('<div>' + i + '' + y + '' + z + '</div>');
IS this what you want. JSFIDDLE
function findthree(nums) {
for (var i=0; in_array(i, nums); i++)
if(in_array(i, nums))
for (var j=i; in_array(j, nums); j++)
if(in_array(j, nums)
for (var k=j; in_array(k, nums); k++)
if(in_array(k, nums) {
// other stuff
}
If you don't want the results to include triplets which have the same digit more than once (112, 133, etc.), then change the initial values to not add the +1...
function findthree(nums) {
for (var i=0; in_array(i, nums); i++)
if(in_array(i, nums))
for (var j=i+1; in_array(j, nums); j++)
if(in_array(j, nums)
for (var k=j+1; in_array(k, nums); k++)
if(in_array(k, nums) {
// other stuff
}

Categories

Resources