Forming an inverted ascii triangle art using JS looping - javascript

Without nesting loops, how are you able to form such an ascii art?
####
###
##
#
This is what I currently have:
function invertTriangle (row) {
var asteric = "*" * row;
for ( var y=row; y>=row; y--){
asteric = asteric - "*";
console.log(asteric);
}
};
invertTriangle(10);
I will appreciate your help and explanation!
Thank you!

Try:
var string = "";
for (var i = 0, j = 4, k = 4; i < 10; i++) {
string += "*";
if (--j === 0) {
j = --k;
string += "\n";
}
}
alert(string);
Hope that helps.

Here's a way of doing it with recursion.
Basically, you call the function with the number of chars you'd like printed on the first line. It then constructs a string with this many characters in it. It then decrements the number of chars wanted and, if this number is greater than 0, calls itself again and adds the new result to the current result. This continues until we get to a line that requires zero characters. At this point, the function no longer calls itself and the fully constructed string is returned to the original caller.
Code:
<!DOCTYPE html>
<html>
<head>
<script>
"use strict";
function byId(e){return document.getElementById(e);}
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded()
{
byId('triTgt').innerText = makeTriString(40);
}
function makeTriString(nStars)
{
var str = '';
for (var i=0; i<nStars; i++)
str += "*";
str += "\n";
nStars--;
if (nStars > 0)
str += makeTriString(nStars);
return str;
}
</script>
<style>
</style>
</head>
<body>
<div id='triTgt'></div>
</body>
</html>

Related

How do i loop a function

I am learning javascript at the moment and i want to ask you about an exercise that i'm trying to finish. This is the quiz i should finish:
https://classroom.udacity.com/courses/ud803/lessons/a7c5b540-51a6-44dc-b2f2-515c9dd6ca4f/concepts/c746623a-eefd-4518-9890-2c5f320b0282
and here is my code. I just dont understand what im doing wrong . can someone explain me.
<html>
<head></head>
<body>
<script>
function makeLine(length) {
var line = "";
for (var j = 1; j <= length; j++) {
line += "* ";
}
return line + "\n";
}
function buildTriangle(widest) {
var x = makeLine(1);
while(x <= widest){
return x;
x++;
}
}
document.write(buildTriangle(10));
</script>
</body>
</html>
I would like to know what i did wrong and how i can fix it, because i always get either "undefined" or nothing at all.
Also i know it's probably a simple mistake but i'm still a beginner so.
after a return statement, any instruction never executed
You have a few issues in function buildTriangle(widest).
var x = makeLine(1);
This will always set x to makeLine(1) doing x++ in the while loop will do nothing.
Further more the x++ is after a return statement so the code will never reach it.
Hope this helps a little.
It's how you actually write the * on your document. I've modified how your buildTriangle works and kept makeLine intact.
(function() {
function makeLine(length) {
var line = "";
for (var j = 1; j <= length; j++) {
line += "* ";
}
return line + "<br/>";
}
function buildTriangle(widest) {
for(var x = 1; x <= widest; x++){
// Moved write inside the loop
// since you want to write each line here
document.write(makeLine(x));
}
}
buildTriangle(10);
})();
<html>
<head></head>
<body>
</body>
</html>
change your function to this
function buildTriangle(widest) {
var x = makeLine(1);
while(x <= widest){
// putting return here would make function execution to stop
// and return the value to the callee, thus not executing
// any statement after this.
x++;//this making this an unreachable code
}
return x;
}
You're almost there.
For the makeline() function, just remove \n so it looks like this:
function makeLine(length) {
var line = "";
for (var j = 1; j <= length; j++) {
line += "* ";
}
return line
}
For buildTriange() you have a few issues: 1) var x = makeLine(1); means that x will always be equal to *, because that is was makeLine(1) will return; 2) the return statement makes x++ unreachable.
Consider this:
function buildTriangle(widest) {
var output = '';
var x = 1;
while(x <= widest){
output += makeLine(x) + '<br>';
x++
}
Now, it build an output. The x variable is a counter. While x is 1 it will add to the output the result of makeLine(1) + '<br>', then it will increase by 1 and run again until the value of x is the same as widest. Then it will return output.
Since document.write() writes html and not plain text. You have to use the line break, not a newline.

Return array type from stack or table - Javascript

I have a problem with my code. Maybe simple, maybe not - for first lets look at this.
var tab = [];
do{
var i = 0;
tab.push(prompt("Write some type of array!"));
i++;
}while(confirm("Next array?"));
for (var i=0; i<tab.length; i++)
document.write(typeof(tab[i])+"<br>");
<!DOCTYPE HTML>
<HTML>
<HEAD>
<meta charset="utf-8">
<meta name="author" content="Donio3d">
</HEAD>
<BODY>
</BODY>
<script src="script.js"></script>
</HTML>
So i want to return a type of array from stack. Everything is always a string.
Is there any way to do this, without checking by IF statement?
To get the typeof of the input you have to first checking if it is a number using Number.isNaN() and for simplicity also used Unary plus (+) operator.
Code:
const tab = [];
const getInputTyeof = i => typeof (!Number.isNaN(+i) ? +i : i);
do {
tab.push(prompt('Write some type of array!'));
} while (confirm('Next array?'));
tab.forEach(input => document.write(getInputTyeof(input) + '<br>'));
Since promt will always return a string in your example you have to figure out if the input may represent a other type or not, using something like this:
var tab = [];
do{
var i = 0;
tab.push(parseType(prompt("Write some type of array!")));
i++;
}while(confirm("Next array?"));
for (var i=0; i<tab.length; i++){
document.write((typeof tab[i])+"<br>");
}
function parseType(e){
if(parseFloat(e) == e && Number.isFinite(parseFloat(e))){
return parseFloat(e);
}
return e;
}
prompt will always return you a string type so you need to make a custom logic with isNaN() to separate out the string and integer values. Something like this below:
var tab = [];
do{
var i = 0;
tab.push(prompt("Write some type of array!"));
i++;
}while(confirm("Next array?"));
var integerType = [];
var stringType = [];
for (var i=0; i<tab.length; i++){
if(isNaN(tab[i])){
stringType.push(tab[i]);
} else {
integerType.push(tab[i]);
}
}
console.log('Integer type array ' + integerType);
console.log('String type array ' + stringType);
var tab = [];
do{
var i = 0;
tab.push(parseType(prompt("Write some type of array!")));
i++;
}while(confirm("Next array?"));
for (var i=0; i<tab.length; i++){
document.write((typeof tab[i])+"<br>");
}
function parseType(e){
if(parseFloat(e) == e && Number.isFinite(parseFloat(e))){
return parseFloat(e);
}
return e;
}
Hey! That is exacly what i was looking for. Thanks for help!

Javascript/For Loop/Basic code/Only runs once

first off yes, I did look at many other codes on this topic and none of those are like mine. I have a very basic code so I apologize if I missed something obvious but I cannot understand why my code will only show one number.
Here is the code.
<!DOCTYPE html>
<head>
</head>
<body>
<div id="test"></div>
<script>
var wildCard = (Math.floor(Math.random() * 5) + 1);
var temp = 1;
for (var i=0; i < 5; i++){
document.getElementById("test").innerHTML = wildCard + "<br />";
temp++;
}
</script>
</body>
</html>
Very basic code, however the only thing is that I only get one random number printed instead of 5 going down in a vertical line. I would like to know what I am missing as to why it will not loop.
Reason why only one number gets printed instead of five is because the DOM node with id test's inner html is replaced in every iteration. When the for-loop ends, you only see the value of the last iteration.
You can use createTextNode and appendChild to complete this task as follows:
var temp = 1;
for (var i=0; i < 5; i++){
const wildCard = (Math.floor(Math.random() * 5) + 1);
const textNode = document.createTextNode(wildCard);
const testDiv = document.getElementById("test");
testDiv.appendChild(textNode)
testDiv.appendChild(document.createElement("br"));
temp++;
}
Generate a new random number in each iteration of the loop, and then assign the full HTML once, after the loop has finished.
<script>
var temp = 1;
var html = "";
for (var i=0; i < 5; i++) {
var wildCard = (Math.floor(Math.random() * 5) + 1);
html += wildCard + "<br/>";
temp++;
}
document.getElementById("test").innerHTML = html;
</script>

for loop for 0 to n number with digits specification

How can I write a for loop for 16 digit number from 0 to n
I want the output to be like:
0000000000000000
0000000000000001
0000000000000002
0000000000000003
0000000000000004
0000000000000005
Tried this but this isn't working:
for(i = 0000000000000000; i < 0000000000000010; i++){
$("#TestDiv").append(i);
}
check out the JSfiddle
Have a look at using the slice method. For example:
var addLeadingZeros = function(number){
var str = "0000000000" + number; // add leading zeros for single digit number
return str.slice(-10); // slice the whole number down from the end
}
for(var i = 0; i < 100; i++){
$("#TestDiv").append(addLeadingZeros(i));
}
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script>
function writeNumber(n){
var nLen = n.toString().length;
var zeroLen = 16-nLen;
var arr = [];
var str = "0";
for(var z=0;z<zeroLen;z++){
arr.push(str);
}
arr.push(n.toString());
return arr.join('');
}
window.onload = function () {
var arr = [];
for(i=0;i<11;i++){
var str = writeNumber(i);
arr.push(str);
}
document.getElementById("testDiv").innerHTML = arr.join('<br>');
};
</script>
<div id="testDiv"></div>
</body>
</html>
More efficient with an array. Maybe it doesn't matter so much when the loop is just 10 items, but you're going to write to the DOM 10 times if you access the DOM inside the loop instead of outside the loop just 1 time. All the
small things adds up, so it may matter.
9. Stop touching the DOM, damnit!
That won't work because for number 00000001 is equal to 1 . You've to use strings.
Use like bellow
var str = '';
var zeros = '0000000000000000'; //string of 16 0's
for(i=0;i<11;i++){
var temp = zeros.slice(i.toString().length); // get the 0's 16-length of i
str += temp+i+'<br>';
}
$("#TestDiv").append(str);
DEMO

Javascript text Array Data Scrambling and Descrambling

I am looking for super fast and compact Javascript code or function to scramble and descramble text stored in Arrays.
I only want this text not readable when the user go into "View Source" mode with the browser.
There are many options like add fixed numbers to the ASCII code or do some boolean calculation on the string like shifting, reversing, change to octal, hex etc.
I need this both for text and number strings. It would be best if the scrambled code where not to complex and not with sign like ", ', #, $, &, / etc.
var c = new Array();
c[0]=new Array( "Name","Home","City","Post code","Telephone","email","Web","Id","Number","xpos","ypos");
c[1]=new Array( "John","Street 123","1234","New York","555-1450123","john#demo.com","www.demo1.com","b",59,306380,565500);
c[2]=new Array( "Poul","Street 1234","2345","New York","555-7010123","poul#demo.com","www.demo2.com","i",113,308396,635477);
c[3]=new Array( "David","Street 12345","3456","New York","555-3111123","david#demo.com","www.demo3.com","i",129,377615,581358);
var Scrambler = function(n) { return ASCII(n)+1...; }
var DeScrambler = function(n) { return ASCII(n)-1...; }
$(function() {
for (var i = 0; i < c[0].length; ++i) {
for (var j = 0; j < (c.length); ++i) {
a[j][i] = DeScrambler(c[j][i]);
}
}
});
Any good idea?
How about ROT13, ROT47, or some other substitution cipher? It's simple to implement, fast, and doesn't increase the length of the string.
If you are scramble the text the user will be able to see the data being transmitted. If you only want to use JS and make it universal perhaps have the server send that data as UTF8 bytes? Also this does not fall under encryption. Encryption and Obfuscation are not the same. I provided a link to a github file that does base and data type conversions. I assume you where looking for something like this.
https://github.com/CubanAzcuy/JSBytes/blob/master/Format.js
(All Byte to UTF8 String Operations are done as unsigned bytes)
(I agree with #mishik minify(ing) your code is one of the best ways to obfuscate)
I made this working solution to solve my problem:
There are few things in this code I would like to work out better if possible.
1) In line 33 I have to use this dirty trick ""+c[i][j]) to convert number in Array to string. But when going back the problem is number is not number anymore in my array! This is very fast but if you have any better idea without loosing the number definition then pls. let me know.
2) I am using 2 version ROT13 and ROT18. I found ROT13 one-line-code version: s.replace(/[a-zA-Z]/g,function(c){return String.fromCharCode((c<="Z"?90:122)>=(c=c.charCodeAt(0)+13)?c:c-26);}); How can I add numbers and -_# letters to those ROT13 in a simple way?
3) As you can see I am using 2D Array to store my code. Any better suggestion?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
var AscII = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#.-";
var ROT18 = "STUVWXYZ0123456789#.-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQR";
var c = new Array();
c[0]=new Array( "Name","Home","City","Post code","Telephone","email","Web","Id","Number","xpos","ypos");
c[1]=new Array( "John","Street 123","1234","New York","438-1450123","john#demo.com","www.demo1.com","b",59,306380,565500);
c[2]=new Array( "Poul","Street 1234","2345","New York","450-7010123","poul#demo.com","www.demo2.com","i",113,308396,6354772);
c[3]=new Array( "David","Street 12345","3456","New York","451-3111123","david#demo.com","www.demo3.com","i",129,377615,581358);
$(function() {
var Normal = function() {
var txt ="";
for (var i = 0; i < c.length; ++i) {
for (var j = 0; j < c[0].length; ++j) {
txt += ""+c[i][j] + ", ";
}
txt += "<br>";
}
$("#kData").html("<b>Normal ASCII<br></b>" + txt);
};
var Convert18 = function(Div, TxtFrom, TxtTo) {
var txt ="";
for (var i = 0; i < c.length; ++i) {
for (var j = 0; j < c[0].length; ++j) {
var ktxtX = decode((""+c[i][j]), TxtFrom, TxtTo);
c[i][j] = ktxtX;
txt += ktxtX + ", ";
}
txt += "<br>";
}
$(Div).html("<b>ROT18 + Numbers + #-_<br></b>" + txt);
};
var Convert13 = function(Div) {
var txt ="";
for (var i = 0; i < c.length; ++i) {
for (var j = 0; j < c[0].length; ++j) {
var ktxtX = rot13(""+c[i][j]);
// s.replace(/[a-zA-Z]/g,function(c){return String.fromCharCode((c<="Z"?90:122)>=(c=c.charCodeAt(0)+13)?c:c-26);});
c[i][j] = ktxtX;
txt += ktxtX + ", ";
}
txt += "<br>";
}
$(Div).html("<b>ROT13<br></b>" + txt);
};
var decode = function (txt, alphabet, substitution) {
return txt.split("").map(function (c) {
if (alphabet.indexOf(c) != -1) { return substitution.charAt(alphabet.indexOf(c)); }
else { return c; }
}).join("");
};
function rot13(str) {
return str.replace(/[a-zA-Z]/g, function(c) {
return String.fromCharCode((c <= 'Z' ? 90 : 122) >= (c = c.charCodeAt(0) + 13) ? c : c - 26);
});
}
Normal();
Convert18("#kData2", AscII, ROT18);
Convert18("#kData3", ROT18, AscII);
Convert13("#kData4");
Convert13("#kData5");
$("#kData6").html("Finised - j:" + c[0].length + " - i:" + c.length);
});
</script>
</head>
<body>
<div id="kData"></div>
<div id="kData2"></div>
<div id="kData3"></div>
<div id="kData4"></div>
<div id="kData5"></div>
<div id="kData6"></div>
</body>
</html>
I put copy of the code on http://jsfiddle.net/kpsphoto/b7MaQ/

Categories

Resources