So im trying to write a function pattern which creates the following pattern upto n number of rows. If the Argument is 0 or a Negative Integer then it should return "" i.e. empty string.
123456
23456
3456
456
56
6
I am trying to understand the solution of this question as below:
function pattern(n){
var output="";
for(i=1;i<n+1;i++){
for(j=i;j<n+1;j++){ //what is the purpose of this j loop?
output += j;
}
if(i!=n) output +="\n"; //I know \n can jump to next line, but what does this if statement mean? why I!=n?
}
return output;
}
// function definition
function pattern(n){
// declare a variable to collect the lines
var output="";
// there are n lines
for(i=1;i<n+1;i++){
// each line starts with the linenumber and ends with n
// so take a loop from i to n
for(j=i;j<n+1;j++){
// collect the numbers of each line as a string in the declared variable
output += j;
}
// if i!=n means: not the last line
if(i!=n) output +="\n";
}
// return the result of this function
return output;
}
UPDATE
But please let me point out, that the given solution is not very smart. Take a look at the following code:
Array.range = function(start, end) {
return Array.apply(null, Array(end+1)).map(function (_, i) {return i;}).slice(start);
}
function pattern(n){
var startValues = Array.range(1,n);
return startValues.map(function(i) { return Array.range(i,n); }).join('\n');
}
http://jsfiddle.net/afmchdwp/
First we define the static Method Array.range which helps us to define number ranges in javascript.
The pattern function can now use this ranges to create the numbers you need.
The first line of the function create a range from 1..n (the startnumbers of the lines).
The second line walks throu this array and transform every value 1..n into a range from the linenumber to n. With .join(), you can combine the characters of each line and combine the lines itself.
UPDATE 2
Here a updated fiddle without comma separated numbers (using join inside the closure): http://jsfiddle.net/afmchdwp/1/
Related
I want to create an animation of strings being looped over and over again one character at a time. I have two arrays in my string:
let stringArray = ['TestOne', 'TestTwo'];
I want to loop over said array repeatedly (string one -> string two -> back to string one -> string two -> ... continuously). I want to print the characters of string one one character at a time. After print all its characters, I will clear the printed string and proceed with the character of string two. Illustration:
T
Te (250 ms after the first char)
Tes (250 ms after the second char)
Test (All characters are printed 250ms after the previous char)
TestO
TestOn
TestOne
T
Te
Tes
Test
TestT
TestTw
TestTwo
... (continue with TestOne again)
The problem is, I want each character to be printed only 250ms after a previously printed character. How can I achieve this?
You could take an array with the indices and an interval for the display.
The array indices contaisn two values at start, [0, 0] which means the first item of stringArray and from this string the first character.
For every loopm, the caracter index gets an increment and this value is checked against the lenght of the string. If greater, then the index of the string gets an increment and the string index is resetted to zero.
To prevent the string index is greater than the actual count of strings, the value is resetted by taking a remainder assignment.
The pattern
(indices => () => {
// ...
})([0, 0])
is an IIFE (immediately-invoked function expression), which takes the array as value for the first parameter. It is a closure over the array and allows to use the resturnd function as callback for the interval.
Tha advantage is to have a data set which is not changable from the outside and is avilable for any call of the callback.
let stringArray = ['TestOne', 'TestTwo'];
setInterval((indices => () => {
document.getElementById('out').innerHTML = stringArray[indices[0]].slice(0, indices[1]);
indices[1]++;
if (indices[1] > stringArray[indices[0]].length) {
indices[0]++;
indices[1] = 0;
}
indices[0] %= stringArray.length;
})([0, 0]), 250)
<pre id="out"></pre>
Well, as long as people are posting solutions, I'll post the obvious, simple one, see comments:
{ // A scoping block so the variables aren't globals
// (unnecessary if you're using modules)
let stringArray = ['TestOne', 'TestTwo'];
let arrayIndex = 0;
let stringIndex = 1;
// Start a timer that will call the callback every 250ms (or so)
setInterval(() => {
// Get the relevant string
const str = stringArray[arrayIndex];
// Output the substring
console.log(str.substring(0, stringIndex));
// Move to the next character
++stringIndex;
// Need to move to next string?
if (stringIndex > str.length) {
// Yes, go back to the beginning of the string and
// move to the next entry in the array, wrapping
// around if we reach the end
stringIndex = 1;
arrayIndex = (arrayIndex + 1) % stringArray.length;
}
}, 250);
}
This part:
arrayIndex = (arrayIndex + 1) % stringArray.length;
is a handy trick for when you have an index (0...n-1) and want to increment it and loop around. Say you have 3 entries, so the indexes are 0, 1, and 2. When you're at 2, (2 + 1) is 3 and 3 % 3 is 0, so it wraps around.
One way you could do this is without using a loop, but instead using a function which takes some parameters so you know how far or long you are in a word, and which word you are currently printing in your array.
Once you are printing with a function, simply add a setTimeout() in the function and then you can control the delay. See https://www.w3schools.com/jsref/met_win_settimeout.asp for more info on timeouts in javascript.
strings = [];
for (var i = 1; i <= "TestOne".length; i++)
strings.push ("TestOne".substring (0, i));
for (var i = 1; i <= "TestTwo".length; i++)
strings.push ("TestTwo".substring (0, i));
var position = 0;
setInterval (() => {
console.log (strings [position++]);
if (position == strings.length) position = 0;
}, 250);
I am working with a javascript program that needs to be formatted a certain way. Basically, I need to have each section of information from an array be a set length, for example 12 characters long, and no more than that.
The problem I am running into comes when a value in the array is NOT 12 characters long. If I have a value that is less than the 12 characters the remaining character allotment needs to be filled with blank spaces.
The length of each section of information varies in size and is not always 12. How can I add X number of blank spaces, should the length not meet the maximum requirement, for each section?
This is where I am at with adding space:
str = str + new Array(str.length).join(' ');
I am pretty sure what I have above is wrong but I believe I am on the right track with the .join function. Any ideas?
EDIT: I was asked to show a wanted outcome. It is a bit complicated because this javascript is being run out of a web report tool and not out of something like Visual Studio so its not traditional JS.
The outcome expected should look something like:
Sample Image
So as shown above the data is in one line, cutting off longer strings of information or filling in blank spaces if its too short for the "column" to keep that nice even look.
try this code and leverage the wonders of the map function:
let say your array is:
var myArr = ["123456789012", "12345678901", "123"];
now just apply this function
myArr.map(function(item){ //evalueate each item inside the array
var strLength = item.length; //apply this function to each item
if (strLength < 12){
return item + ' '.repeat(12-item.length) //add the extra spaces as needed
} else {
return item; // return the item because it's length is 12 or +
}
})
What you are looking for is the ' '.repeat(x) - where x is the times you want to repeat the string you have set, it could be '*'.repeat(2) and you would get '**', if you want to understand more about it look at the docs
depending on which version of javascript, this might work:
if (str.length < 12) str += ' '.repeat(12 - str.length);
Not exactly sure how you're setup -- but something like the following will accept an array and return another array with all its values being 12 characters in length.
var array = ['Test', 'Testing', 'Tested', 'This is not a Test'];
var adjustedArray = correctLength(array, 12);
function correctLength(array, length) {
array.map(function(v, i) {
if (array[i].length < length) {
array[i] += Array((length+1) - array[i].length).join('_');
}
// might not need this if values are already no greater than 12
array[i] = array[i].substring(0, length);
});
return array;
}
console.log(adjustedArray);
I would like to create a program that takes a number is input, such as: 12345 and then splits this number into 2 digit numbers and store it in a array. The array must look like this: [0]=45 [1]=23 [2]=1 . This means that the splitting of the numbers must start from the last digit of the number and not the first.
This is what I have until now:
var splitCount = []; // This is the array in which we store our split numbers
//Getting api results via jQuery's GET request
$.get("https://www.googleapis.com/youtube/v3/channels?part=statistics&id=UCJwchuXd_UWNxW-Z1Cg-liw&key=AIzaSyDUzfsMaYjn7dnGXy9ZEtQB_CuHyii4poc", function(result) {
//result is our api answer and contains the recieved data
//now we put the subscriber count into another variable (count); this is just for clarity
count = result.items[0].statistics.subscriberCount;
//While the subscriber count still has characters
while (count.length) {
splitCount.push(count.substr(0, 2)); //Push first two characters into the splitCount array from line 1
count = count.substr(2); //Remove first two characters from the count string
}
console.log(splitCount) //Output our splitCount array
});
but the problem with this is that if there are 5 digits for example: 12345 the the last digit will be in an array by itself like this: [0]=12 [1]=34 [2]=5 but I need the last array to have 2 digits and the first should be the one with one digit instead like this: [0]=1 [1]=23 [2]=45
very crude but this should work assuming the string is always numbers:
input = "12345"
def chop_it_up(input)
o = []
while input.length > 0
if input.length <= 2
o << input
else
o << input[-2..input.length]
end
input = input[0..-3]
chop_it_up(input)
end
return o
end
I probably do sth like this :
int[] fun(int x){
int xtmp = x;
int i = 0;
int len = String.valueOf(x).length();
// this is a function for java, but you can probably find
//an equivalent in whatever language you use
int tab[(len+1)/2];
while(xtmp > 1){
tab[i] = xtmp%100;
xtmp = int(xtmp/100); // here you take the integer part of your xtmp
++i;
}
return tab;
}
I've a simple problem from Hacker Rank.
There are N strings. Each string's length is no more than 20 characters. There are also Q queries. For each query, you are given a string, and you need to find out how many times this string occurred previously. The first line contains , the number of strings. The next N lines each contain a string. The N + 2nd line contains , the number of queries.
The following Q lines each contain a query string.
Sample Input
4
aba
baba
aba
xzxb
3
aba
xzxb
ab
Sample Output
2
1
0
Here's the provided code,
function processData(input) {
//Enter your code here
}
process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
_input += input;
});
process.stdin.on("end", function () {
processData(_input);
});
The solution to the problem is simple.
Initialize a hashmap. Enter the values in the N strings in the hashmap against occurence count.
var map = {};
if(!map[input])map[input]++;
else map[input] = 1;
And then for each query return the get on the respective key.
The issue is I'm new to javascript and have no clue about node. Can someone help me understand the code and help me in figuring out the scopes in which the respective data structures will have to instantiated.
You need to put your code in :
function processData(input) {
// split your input and access it
//your logic
var map = {};
if(!map[input])map[input]=1;
else map[input] +=1;
//your output
console.log('...');
}
Explaination
Start reading from stdin so we don't exit.
process.stdin.resume();
Reads the input data
process.stdin.on("data", function (input) {
_input += input;
});
On completion of data calls the end event is fired.
process.stdin.on("end", function () {
processData(_input);
});
I have the following function that encrypts a string and I was hoping for a function that reverses the process.
function encryptStr(thisString)
{
retString = "";
/* Make retString a string of the 8-bit representations of
the ASCII values of its thisCharacters in order.
EXAMPLE: "abc" --> "011000010110001001100011"
since the ASCII values for 'a', 'b' and 'c'
are 97=01100001, 98=01100010 and 99=01100011
respectively
*/
for (i = 0, j = thisString.length; i < j; i++)
{
bits = thisString.charCodeAt(i).toString(2);
retString += new Array(8-bits.length+1).join('0') + bits;
}
/* Compress retString by taking each substring of 3, 4, ..., 9
consecutive 1's or 0's and it by the number of such consecutive
thisCharacters followed by the thisCharacter.
EXAMPLES:
"10101000010111" --> "10101401031"
"001100011111111111111" --> "0011319151"
*/
retString = retString.replace(/([01])\1{2,8}/g, function($0, $1) { return ($0.length + $1);});
return retString;
}
I tried to make a function and I'm probably doing it wrong because it's 50 lines already. I'm realizing that there's tons of error checking that needs to go on. For instance, I just realized a potential problem because JavaScript characters don't span the entire 127 ASCII values. Should I just give up? Is this a futile problem?
First, find the numbers in the string which are not 0 or 1. Then, expand them in the opposite way that the original function collapsed them. You can again use String.prototype.replace() here with a replacement function...
str.replace(/([2-9])([01])/g,
function(all, replacementCount, bit) {
return Array(+replacementCount + 1).join(bit);
});
Then, simply decode the bit stream back into characters with String.fromCharCode(). You'd need to chunk the stream into 8 bit chunks, and then perform the conversion. I chose to use Array.prototype.reduce() as it's quite suited to this task. Alternatively, you could use String.fromCharCode.apply(String, chunks.map(function(byte) { return parseInt(byte, 2); })) to get the resulting string.
Something like...
str.split(/(.{8})/g).reduce(function(str, byte) {
return str + String.fromCharCode(parseInt(byte, 2));
}, "");
Put it together, and you get a function like...
function decryptStr(thisString) {
return thisString.replace(/([2-9])([01])/g,
function (all, replacementCount, bit) {
return Array(+replacementCount + 1).join(bit);
}).split(/(.{8})/g).reduce(function (str, byte) {
return str + String.fromCharCode(parseInt(byte, 2));
}, "");
}
jsFiddle.
Also, remember to place var in front of your variable declarations, otherwise those variable identifiers will leak to the containing scope until they're resolved (which is usually the global object).