Javascript to generate dynamic string of numbers - javascript

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)

Related

All possible words of any length from the input letters, javascript [duplicate]

I'm trying to create a function in JavaScript that given a string will return an array of all possible combinations of the letters with each used at most once, starting with the shortest. e.g for the string ABC it would return:
A
B
C
AB
AC
ABC
I could use loops like so:
for(i=0; i<string.length; i++) {
//add string[i]
}
for(i=0; i<string.length; i++) {
for(a=i; a<string.length; a++) {
//add string[i]+string[a]
}
}
for(i=0; i<string.length; i++) {
for(a=i; a<string.length; a++) {
for(b=a; b<string.length; b++) {
//add string[i]+string[a]+string[b]
}
}
}
But I don't know the length of the string, so wouldn't know how many loops to use.
Any ideas?
Edit: I'm not asking for permutations, abc and acb shouldn't both be returned. Also the shortest being first in the array is important.
This is not homework. It's for a program to solve a 'lights-out' type game.
This is a recursive solution that I think is very easy to understand.
var tree = function(leafs) {
var branches = [];
if (leafs.length == 1) return leafs;
for (var k in leafs) {
var leaf = leafs[k];
tree(leafs.join('').replace(leaf, '').split('')).concat("").map(function(subtree) {
branches.push([leaf].concat(subtree));
});
}
return branches;
};
console.log(tree("abc".split('')).map(function(str) {
return str.join('')
}))
You could use a nasty trick and increase a counter and use its binary representation as flags:
function combine(str){
const result = [];
for(let i = 1; i < Math.pow(2, str.length) - 1; i++)
result.push([...str].filter((_, pos) => (i >> pos) & 1).join(""));
return result;
}
console.log(combine('abcd'));
Jsbin
This is what I ended up using.
var combinations = function (string)
{
var result = [];
var loop = function (start,depth,prefix)
{
for(var i=start; i<string.length; i++)
{
var next = prefix+string[i];
if (depth > 0)
loop(i+1,depth-1,next);
else
result.push(next);
}
}
for(var i=0; i<string.length; i++)
{
loop(0,i,'');
}
return result;
}
This is usiing loop as you expected easiest way.. good luck
function mixString() {
var inputy = document.getElementById("mixValue").value
var result = document.getElementById("mix-result")
result.innerHTML=""
for (var i = 0 ; i < inputy.length; i++) {
for (var b = 0 ; b < inputy.length; b++) {
if (i == b) {
result.innerHTML += inputy.charAt(i) + ","
}
else
{
result.innerHTML += inputy.charAt(i) + inputy.charAt(b) + ","
}
}
}
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">JavaScript string combination
</div>
<div class="panel-body">
<input id="mixValue" class="form-control" />
<input type="button" onclick="mixString()" value="click" />
<div id="mix-result"></div>
</div>
</div>
</div>
function combinations(var1) {
var temp;
for (var i = 0; i < var1.length; i++) {
var2 = "";
temp = i;
while (temp < var1.length) {
var2 = var2.concat(var1.charAt(temp));
// console.log(var2)
if (i == var1.length - 1)
document.getElementById('result').innerHTML += var2;
else
document.getElementById('result').innerHTML += var2 + ',';
temp++;
}
}
}
You couldm take an iterative and recursive approach by using the character at the given key or not.
function combine(string) {
function iter(i, temp) {
if (i >= string.length) {
result.push(temp);
return;
}
iter(i + 1, temp + string[i]);
iter(i + 1, temp);
}
var result = [];
iter(0, '');
return result;
}
console.log(combine('jump'));
.as-console-wrapper { max-height: 100% !important; top: 0; }
The accepted solution as of July 29, 2019 allows for duplicate strings to be returned in the array. The following adjustment fixes that little issue by adding a condition to the push.
// however, we don't want duplicates so...
if (!result.includes(next)) {
result.push(next);
}
Generators allow a very clean implementation:
// Very short generator produces all possible strings composed of the given chars!
let allStrings = function*(chars) {
yield '';
for (let prefix of allStrings(chars)) for (let c of chars) yield `${prefix}${c}`;
};
// Render the first 1000 strings
document.body.style.fontFamily = 'monospace';
let count = 0;
for (let str of allStrings('abcd')) {
let div = document.createElement('div');
div.innerHTML = `${(count + 1).toString().padStart(4, '0')}: ${str}`;
document.body.appendChild(div);
if (count++ > 1000) break;
}
Note that the very first result from allStrings is the empty string. If it's crucial to avoid this the following implementation can be used:
let allStrings = function*(chars, includeEmpty=false) {
if (includeEmpty) yield '';
for (let prefix of allStrings(chars, true)) for (let c of chars) yield `${prefix}${c}`;
};
//all combinations of a string
// dog => d,do,dog,og,g
function combinationString(){
let str = 'dog';
let combinationArray = [];
for(i=0; i< str.length; i++){
for(j=i+1; j<=str.length; j++){
combinationArray.push(str.slice(i,j));
}
}
console.log("Combination ", combinationArray);
}
combinationString()

How to make characters in a string repeat using Javascript?

How can I make individual characters within a string repeat a given amount of times?
That is, how do I turn "XyZ" into "XXXyyyZZZ"?
Try this:
var foo = 'bar';
function makeString(str, repeat) {
var str = Array.prototype.map.call(str, function(character) {
var nascentStr = '';
while (nascentStr.length < repeat) {
nascentStr += character;
}
return nascentStr;
}).join('');
return str;
}
alert(makeString(foo, 3));
You'll need to use a combination of a few functions. First you'll need to split the string into individual characters:
var charArray = "XyZ".split('');
Once you have it split up, you can use a combination of the .map function and a nifty little trick of javascript Array.
var someMultiplier = 5;
var duplicatedArray = charArray.map(function(char) {
return Array(someMultiplier).join(char);
});
At that point, you have an array of strings that have the duplicate letters, and you can combine them back with .join
var dupString = duplicatedArray.join('');
dupString === "XXXXXyyyyyZZZZZ
Sounds straight forward. You can run this in your browser's console:
var my = 'XyZ';
function repeat(str, times) {
var res = '';
for (var i in str) {
var char = str[i];
for (var j=0; j < times; j++) {
res += char;
}
}
return res;
}
var his = repeat(my, 3);
console.log(his);
you have not mentioned what will happen if input will be like xyxzy. Assuming it will be xxxyyxxxzzzyyy
// function takes input string & num of repitation
function buildString(input, num) {
var _currentChar = ""; // Final output string
for (var m = 0; m < input.length; m++) {
//call another function which will return XXX or yyy or zzz & then finally concat it
_currentChar += _repeatString((input.charAt(m)), num);
}
}
// It will return XXX or yyy or ZZZ
// takes individual char as input and num of times to repeat
function _repeatString(char, num) {
var _r = "";
for (var o = 0; o < num; o++) {
_r += char;
}
return _r
}
buildString('XyZ', 3)
jsfiddle for Example
function repeatStringNumTimes(str, num) {
let valueCopy = str
if (num > 0) {
for (var i = 0; i < num - 1; i++) {
valueCopy = valueCopy.concat(str)
}
} else {
valueCopy = ""
}
return valueCopy;
}
repeatStringNumTimes("abc", 3);
These days can be done a lot easier:
const repeater = (str, n) => [...str].map(c => c.repeat(n)).join('');
alert(repeater('XyZ', 3));

Getting a nth element from a string

How can I get a certain nth element from a string. Like if I want to get every 3rd element from the word GOOGLE how can i do that. SO far i've done this but i dont know what to type after the If
function create_string( string ) {
var string_length=string.length;
var new_string=[];
for( var i=0; i<string_length; i++) {
if(string[i]%3==0) {
}
new_string.push(string[i]);
}
return new_string;
}
Use the charAt() function of String which returns the char at a specific index passed to the function. Using charAt, I have created a script that will return every third character.
var result = "";
for(var i = 2; i < test.length; i+=3){
result += test.charAt(i);
}
If you would like to turn this script into a more reusable function:
var test = "GOOGLE";
function getEveryNthChar(n, str){
var result = "";
for(var i = (n-1); i < test.length; i+=n){
result += str.charAt(i);
}
return result;
}
alert(getEveryNthChar(1,test));
alert(getEveryNthChar(2,test));
alert(getEveryNthChar(3,test));
alert(getEveryNthChar(4,test));
Working Demo: http://jsfiddle.net/Q7Lx2/
Documentation
How about this?
function create_string( string ) {
var string_length=string.length;
var new_string=[];
for( var i=2; i<string_length; i+=3) { // instead of an if, use +=3
new_string.push(string.charAt(i));
}
return new_string.join(""); // turn your array back into a string
}
Note that if you start making this compact, you'll end up with the same answer as Kevin's ;-)
function create_string( s ) {
var new_string = '';
for( var i=2; i<s.length; i+=3) { // instead of an if, use +=3
new_string += s.charAt(i);
}
return new_string;
}
Here's a function that will work for any number, not just 3:
function stringHop(s, n) {
var result = "";
for (var i = 0; i < s.length; i+= n) {
result += s.charAt(i);
}
return result;
}
var foo = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var bar = stringHop(foo, 2); // returns "ACEGIKMOQSUWY"
var baz = stringHop(foo, 3); // returns "ADGJMPSVY"
String.charAt(index) will return the character at the specified index, from 0 to String.length - 1. So:
String.prototype.every = function(n) {
var out = '';
for (var i = 0; i < this.length; i += n) {
out += this.charAt(i);
}
return out;
}
var str = "GOOGLE";
console.log(str.every(3)) // Outputs: GG
If you don't want to include the first character, then change the for loop to:
for (var i = n - 1; i < this.length; i += n) {

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..

get all combinations for a string

I'm trying to create a function in JavaScript that given a string will return an array of all possible combinations of the letters with each used at most once, starting with the shortest. e.g for the string ABC it would return:
A
B
C
AB
AC
ABC
I could use loops like so:
for(i=0; i<string.length; i++) {
//add string[i]
}
for(i=0; i<string.length; i++) {
for(a=i; a<string.length; a++) {
//add string[i]+string[a]
}
}
for(i=0; i<string.length; i++) {
for(a=i; a<string.length; a++) {
for(b=a; b<string.length; b++) {
//add string[i]+string[a]+string[b]
}
}
}
But I don't know the length of the string, so wouldn't know how many loops to use.
Any ideas?
Edit: I'm not asking for permutations, abc and acb shouldn't both be returned. Also the shortest being first in the array is important.
This is not homework. It's for a program to solve a 'lights-out' type game.
This is a recursive solution that I think is very easy to understand.
var tree = function(leafs) {
var branches = [];
if (leafs.length == 1) return leafs;
for (var k in leafs) {
var leaf = leafs[k];
tree(leafs.join('').replace(leaf, '').split('')).concat("").map(function(subtree) {
branches.push([leaf].concat(subtree));
});
}
return branches;
};
console.log(tree("abc".split('')).map(function(str) {
return str.join('')
}))
You could use a nasty trick and increase a counter and use its binary representation as flags:
function combine(str){
const result = [];
for(let i = 1; i < Math.pow(2, str.length) - 1; i++)
result.push([...str].filter((_, pos) => (i >> pos) & 1).join(""));
return result;
}
console.log(combine('abcd'));
Jsbin
This is what I ended up using.
var combinations = function (string)
{
var result = [];
var loop = function (start,depth,prefix)
{
for(var i=start; i<string.length; i++)
{
var next = prefix+string[i];
if (depth > 0)
loop(i+1,depth-1,next);
else
result.push(next);
}
}
for(var i=0; i<string.length; i++)
{
loop(0,i,'');
}
return result;
}
This is usiing loop as you expected easiest way.. good luck
function mixString() {
var inputy = document.getElementById("mixValue").value
var result = document.getElementById("mix-result")
result.innerHTML=""
for (var i = 0 ; i < inputy.length; i++) {
for (var b = 0 ; b < inputy.length; b++) {
if (i == b) {
result.innerHTML += inputy.charAt(i) + ","
}
else
{
result.innerHTML += inputy.charAt(i) + inputy.charAt(b) + ","
}
}
}
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">JavaScript string combination
</div>
<div class="panel-body">
<input id="mixValue" class="form-control" />
<input type="button" onclick="mixString()" value="click" />
<div id="mix-result"></div>
</div>
</div>
</div>
function combinations(var1) {
var temp;
for (var i = 0; i < var1.length; i++) {
var2 = "";
temp = i;
while (temp < var1.length) {
var2 = var2.concat(var1.charAt(temp));
// console.log(var2)
if (i == var1.length - 1)
document.getElementById('result').innerHTML += var2;
else
document.getElementById('result').innerHTML += var2 + ',';
temp++;
}
}
}
You couldm take an iterative and recursive approach by using the character at the given key or not.
function combine(string) {
function iter(i, temp) {
if (i >= string.length) {
result.push(temp);
return;
}
iter(i + 1, temp + string[i]);
iter(i + 1, temp);
}
var result = [];
iter(0, '');
return result;
}
console.log(combine('jump'));
.as-console-wrapper { max-height: 100% !important; top: 0; }
The accepted solution as of July 29, 2019 allows for duplicate strings to be returned in the array. The following adjustment fixes that little issue by adding a condition to the push.
// however, we don't want duplicates so...
if (!result.includes(next)) {
result.push(next);
}
Generators allow a very clean implementation:
// Very short generator produces all possible strings composed of the given chars!
let allStrings = function*(chars) {
yield '';
for (let prefix of allStrings(chars)) for (let c of chars) yield `${prefix}${c}`;
};
// Render the first 1000 strings
document.body.style.fontFamily = 'monospace';
let count = 0;
for (let str of allStrings('abcd')) {
let div = document.createElement('div');
div.innerHTML = `${(count + 1).toString().padStart(4, '0')}: ${str}`;
document.body.appendChild(div);
if (count++ > 1000) break;
}
Note that the very first result from allStrings is the empty string. If it's crucial to avoid this the following implementation can be used:
let allStrings = function*(chars, includeEmpty=false) {
if (includeEmpty) yield '';
for (let prefix of allStrings(chars, true)) for (let c of chars) yield `${prefix}${c}`;
};
//all combinations of a string
// dog => d,do,dog,og,g
function combinationString(){
let str = 'dog';
let combinationArray = [];
for(i=0; i< str.length; i++){
for(j=i+1; j<=str.length; j++){
combinationArray.push(str.slice(i,j));
}
}
console.log("Combination ", combinationArray);
}
combinationString()

Categories