RandomString Error In Output - javascript

Is there any way to get this using randomString..
function randomString(length, chars) {
var result = '';
var i;
for (i = 0; i <= 100; i++) result += chars[Math.round(Math.random() * (chars.length - 1))];
return result;
}
var rString = randomString(100, '0');
I need the output like this..
0
00
000
0000
00000
000000
0000000
00000000 and so on till 100

Here is working code.
I renamed the function because it is not a randomString function.
http://jsfiddle.net/8rn5gpze/
function bar(length, chars) {
var result ='', last = '';
for (i = 0; i <= length; i++){
last += chars;
result += last;
result += '<br>';
}
return result;
}
var foo = bar(100, '0');

Try the following script
<script language="javascript">
function randomString(length, chars) {
var result = '';
var i;
var sequencecheck = 1;
var finalresult = '';
for (i = 0; i <= 100; i++)
{
result += chars[Math.round(Math.random() * (chars.length - 1))];
finalresult+=result
if(result.length == sequencecheck)
{
finalresult += "<br/>"
sequencecheck++;
}
}
return finalresult;
}
var rString = randomString(100, '0');
document.write(rString);
</script>
Hope it helps!

If you want a simple output to the console just use this:
function randomString(length, chars) {
var result = '';
for (i = 1; i <= length; i++) {
result += chars;
console.log(result);
}
}

To get your output you could use this function: demo
HTML
<div></div>
For demonstration purposes.
JavaScript
function strTimes(str,times){
var fullStr = "";
for( var i = 0 ; i < times ; i ++ )
fullStr += str;
return fullStr;
}
function outputZeroes(levels,outputToElement){
var newLine = ( outputToElement ) ? "<br>" : "\n";
var str = "";
for( var i = 1 ; i < levels ; i ++ ){
str += strTimes("0",i);
str += newLine;
}
return str;
}
var div = document.querySelector("div");
div.innerHTML = outputZeroes(10,true);
The outputZeroes() function accepts to parameters, the first one is the amount of levels you want, and the second one is a boolean that decides which new line should be used, if set to true, it will be <br> for outputting to html elements, and if false it will be \n for outputting to anything else, by default is false.
Hope it helps!

Related

can anyone figure out the bug in my code?

The function is supposed to solve the following problem, but there is something wrong in it.
The problem:
Repeat a given string str (first argument) for num times (second argument). Return an empty string if num is not a positive number.
function repeatStringNumTimes(str, num) {
var result = '';
for(let i = 0; i < num; i++){
result += 'str';
}
return result;
}
repeatStringNumTimes("abc", 3);
two problems. first 'str' will give you a literal. you want the variable str. second, once you have the result you need to display it.
function repeatStringNumTimes(str, num) {
var result = '';
for(let i = 0; i < num; i++){
result += str;
}
return result;
}
var result = repeatStringNumTimes("abc", 3);
console.log(result);
you will have to add the old string to the new one and don't forget the space between them
function repeatStringNumTimes(str, num) {
var result = '';
for(let i = 0; i < num; i++){
result = result + str + ' ';
}
return result;
}
repeatStringNumTimes("abc", 3);
First you're not returning if the num is not positive. Second, it should be str and not 'str' if you want to repeat the variable.
function repeatStringNumTimes(str, num) {
var result = '';
if (num < 1) return; //return if num is not postive
for(let i = 0; i < num; i++){
result += str;
}
return result;
}
var res = repeatStringNumTimes("abc", 3);
console.log(res)

Javascript to generate dynamic string of numbers

I have a requirement to write a function to generate the below dynamic string.
Here are some examples of what the output should look like for a function argument of 6, 5, and 4, respectively (Actually I am flexible with passing the argument).
123456789112345678921234567893123456789412345678951234567896
12345678911234567892123456789312345678941234567895
1234567891123456789212345678931234567894
The length of the output will always be a multiple of 10.
Should I use normal JS arrays OR can I use some ready jQuery methods to acheive this ?
Here is the code, I think it will help you
function dynamicNumber(n){
var s="";
for(i=1;i<=n;i++){
s=s+"123456789"+i;
}
return s;
}
Try something like this.
function generateString(l) {
var x = "123456789",
t = "";
for (i = 1; i < (l + 1); i++) {
t += x + i;
}
return t;
}
Example below:
function generateString(l) {
var x = "123456789",
t = "";
for (i = 1; i < (l + 1); i++) {
t += x + i;
}
return t;
}
console.log(generateString(6))
console.log(generateString(5))
console.log(generateString(4))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here is how I do it:
function dynamic_string(val){
var strin = "123456789"
var result = ""
for(var i = 1; i <= val; i++){
result += strin;
result += i;
}
console.log(result)
}
dynamic_string(6)
What about (ES6):
function getString(amount) {
let sNumber = '';
for(let i=1;i<=amount;i++) {
sNumber += '123456789' + i;
}
return sNumber;
}
Try this way
var nu=5;
for(var i=1;i<=nu;i++){
for(j=1;j<=9;j++){
console.log(j)
}
console.log(i)
}
jsbin
You can use this simple logic...
var str = '123456789';
var len=5;
var out = ''
for(var i=1;i<=len;i++){out+=str+i;}
console.log(out)

Loop to print iterations separated with a comma, with no comma at the end

I'm a student and am writing a JavaScript "for" loop that prints into innerHTML. Every concatenation of the string is added to the last followed by a comma. how do I make it so the comma is not printed after the last iteration? Just for piece of mind, the commas aren't part of the assignment, I'm just trying to add practical application. no jQuery tho please
window.onload = function(){
var mySeven = 0;
var printSeven = document.getElementById('multiples_seven');
for (i=1; i <= 1000; i++){
if (i % 7 == 0){
mySeven += i;
printSeven.innerHTML += i + ',' + ' ';
}
}
};
Thanks!
You should use join() instead. It's much cleaner and you don't need to worry about edge cases:
var printSeven = document.getElementById('multiples_seven');
var sevens = [];
for (i=1; i <= 1000; i++){
if (i % 7 == 0){
sevens.push(i);
}
}
printSeven.innerText = sevens.join(", ");
Or an approach that avoids the if() statement and unnecessary iterations:
var printSeven = document.getElementById('multiples_seven');
var sevens = [];
for (i = 7; i <= 1000; i += 7){
sevens.push(i);
}
printSeven.innerText = sevens.join(", ");
And for the sake of understanding, here's how you could do this without join():
var printSeven = document.getElementById('multiples_seven');
var maxValue = 1000;
var list = "";
for (i = 7; i <= maxValue; i += 7){
list += i;
if(i + 7 <= maxValue){
list += ", ";
}
}
printSeven.innerText = list;
Use this function:
function reorderData(){
var sevens = Array();
var printSeven = document.getElementById('multiples_seven');
for (i=1; i <= 1000; i++){
if (i % 7 == 0){
sevens.push(i);
}
}
var newDisplaySelectedArray = sevens.join(",");
jQuery( "#multiples_seven" ).val(newDisplaySelectedArray);
}
First off it is better to not manipulate the DOM inside a loop. You should construct your output in a string or array then add it to the DOM in a single operation :
window.onload = function () {
var mySeven = '';
var printSeven = document.getElementById('multiples_seven');
for (i=1; i <= 1000; i++){
if (i % 7 == 0){
mySeven += i + ', ';
}
}
printSeven.innerHTML += mySeven;
};
To delete the trailing comma you have two options : don't add it in the first place or remove it before adding it to the DOM.
Most other answers have concentrated on not adding it, here is a solution which removes it :
window.onload = function () {
var mySeven = '';
var printSeven = document.getElementById('multiples_seven');
for (i=1; i <= 1000; i++){
if (i % 7 == 0){
mySeven += i + ', ';
}
}
printSeven.innerHTML += mySeven.slice (0, -2);
};
A word of caution, if your for loop does not execute at least one iteration you may remove characters you want to display. In the generic case it is easier to build an array and use the join function as shown in other answers here.
It's easier to check if you are at the first item than if you are at the last, so simply add the commas before the number:
window.onload = function(){
var mySeven = 0;
var printSeven = '';
for (i = 1; i <= 1000; i++) {
if (i % 7 == 0){
mySeven += i;
printSeven += (printSeven.length > 0 ? ', ' : '') + i;
}
}
document.getElementById('multiples_seven') += printSeven;
};

JavaScript Decrementing Alphabet Function

New to the JavaScript language and need help creating a function which generates the following display.
abcdefghijklmnopqrstuvwxyz
bcdefghijklmnopqrstuvwxyz
cdefghijklmnopqrstuvwxyz
defghijklmnopqrstuvwxyz
.... and so on, all the way down to
xyz
yz
z
I am not asking for handouts, just a little kickstart for a beginner to get started! Links, hints, tips, anything helps! Thanks!
Arrays and loops are powerful when combined.
var alphabet = "abcdefghijklmnopqrstuvwxyz".split('');
console.log(alphabet.join(''));
while (alphabet.​length > 0) {
alphabet.shift();
console.log(alphabet.join(''));
}​​​
Edit:
If you really need your decremented alphabet to be left-padded, you can use this:
var alphabet = "abcdefghijklmnopqrstuvwxyz";
var letters = alphabet.split('');
var addPadding = (function (minLength) {
return function (shortString) {
if (shortString.length < minLength) {
return new Array(
minLength - shortString.length + 1
).join(' ') + shortString;
}
};
}(alphabet.length));
console.log(alphabet);
while (letters.length > 0) {
letters.shift();
console.log(addPadding(letters.join('')));
}
Edit:
Here is a much simpler answer:
function decrementingAlphabet () {
var alphabet = 'abcdefghijklmnopqrstuvwxyz';
function iterate(spaces, letters) {
if (letters.length > 0) {
console.log(spaces + letters);
iterate(spaces + ' ', letters.substring(1));
} else {
return;
}
}
iterate('', alphabet);
}
This is simple example.
var str = '';
for (var s=0; s < 26; ++s) {
str = '';
for (var i=0; i < 26 - s; ++i) {
str += String.fromCharCode(97+s+i);
}
document.write(str + "<br/>");
}
​
See http://jsfiddle.net/G5Gds
Hmm, maybe this will help put you on the right track?
var str = '';
// Find out what 'a' is in ASCII
var baseLetterCode = 'a'.charCodeAt(0);
// Loop once for each letter
for (var i = 0; i < 26; ++i) {
// Append to string
str += String.fromCharCode(baseLetterCode + i);
}
In character codes, small alphabets lie from 97 onwards(97 for a). You need to use 2 for loops to print such series.
Here is your jsfiddle demo:
var display='';
for(var i=97;i<123;i++){
var s='';
for(var j=i;j<123;j++){
s+= String.fromCharCode( j );
}
display+=s;
}
alert(display);
(function() {
var theENalphabet = [];
for (var charNow = "a".charCodeAt(0); charNow <= "z".charCodeAt(0); charNow += 1) {
theENalphabet.push(String.fromCharCode(charNow));
}
var isNow = 0;
function decrAlph(startAt) {
var alphString = "";
for (var i = startAt; i < theENalphabet.length; i += 1) {
alphString += theENalphabet[i];
}
console.log(alphString);
isNow++;
while (isNow < theENalphabet.length) {
decrAlph(startAt + 1);
}
};
decrAlph(0);
})();
The charCode getting could be abstracted into a function:
var getCharCode = function(el){
return String.prototype.charCodeAt.call(el, 0);
};
getCharCode("a"); // returns 97..

why is my chaine.charAT not a function and what else is broken in here

function chainePair(chaine) {
var longueur = chaine.length;
for (var i = 0; i <= longueur; i += 2) {
var result = chaine.charAT(i);
document.getElementById("reponse1").innerHTML = result + " ";
}
}​
I am trying to make this function write every 2 letter of my string in the space allocated by reponse1 id. example: the string monster would show: m n t r
JavaScript is case sensitive, use .charAt() method:
// ----------------------v
var result = chaine.charAt(i);
function chainePair(string){
var result = "";
for(var i=0; i<string.length; i+=2){
result += string[i];
}
document.getElementById("response1").innerHTML = result+" ";
}

Categories