Adding asterisks to array? - javascript

I'm trying to add elements as asterisks inside array based on number of elements. Basically If numberOfRows is 3 then I want this output:
[
' * ',
' *** ',
'*****'
]
I'm struggling on setting asterisks using the index. Can anyone point me in the right direction? Thanks a lot!
Here's my code:
function myFunction(numberOfRows) {
var arr = [];
var value = "";
var asterisk = "*"; // Need to update this based on number of rows
for (var i = 1; i <= numberOfRows; i++) {
value += asterisk;
arr.push(value);
}
return arr;
}

Got it working! Here's a perfect solution.
function myFunction(n) {
let arr = [];
for(let f = 1; f <= n; f++) {
arr.push(' '.repeat(n - f) + '*'.repeat(f + f - 1) + ' '.repeat(n - f));
}
return arr;
}
console.log(myFunction(3));

Try something like this;
function myFunction(numberOfRows) {
var arr = [];
var value = "";
var slots = numberOfRows * 2 - 1;
var spaceSlots, asteriskSlots, spaces;
for (var i = 0; i < numberOfRows; i++) {
asteriskSlots = i * 2 + 1;
spaceSlots = Math.floor((slots - asteriskSlots)/2);
spaces = new Array(spaceSlots).fill(' ').join('');
value = spaces + '*'.repeat(asteriskSlots) + spaces;
arr.push(value);
}
return arr;
}
console.log(myFunction(20));

Related

Delete "," from Strig (and return RGB\n String)

so I've been stuck at this problem for a few days:
My Input is this:
"255,255,255,10,251,91,31,4,220,220,220,1"
Its a String with 3 different RGB values, which also come with a number which indicates their quantity going from hightest to lowest.
You could translate the String from above to:
"RED1, GREEN1, BLUE1, QUANTITY1, RED2, GREEN2 ... "
While the 1 stands for the first color and 2 for the second and so on.
What I need to return is the first color without its quantity.
So my output should look like this:
"255,255,255,251,91,31,220,220,220"
I've tried various of things, one is this function:
var firstC, secondC, thirdC;
var pointer = "firstC";
function getEachColorValue(color) {
var startIndex = 0;
var endIndex = 0;
for (var i = 0; i < color.length; i++) {
if (color.charAt(i) == ",") {
endIndex = i;
if (pointer == "firstC") {
firstC = color.substring(startIndex, endIndex);
startIndex = endIndex + 1;
pointer = "secondC";
} else if (pointer == "secondC") {
secondC = color.substring(startIndex, endIndex);
startIndex = endIndex + 1;
pointer = "thirdC";
} else if (pointer == "thirdC") {
thirdC = color.substring(startIndex, endIndex);
startIndex = endIndex;
pointer = "firstC";
}
}
}
}
This pushes RED1 in firstC, GREEN1 in secondC and BLUE1 in thirdC
I thought about doing that one time, use a function to write firstC, secondC, thirdC into an array, reset them. Then cut col3 into a substring without the first color pallet, then repeat.
// Global variables
var stringHolder;
var newString;
var counter = 0;
var colorSetHT = new Array;
// main
createSubstring(col3);
function createSubstring(color) {
var startIndex = 0;
var endIndex = 0;
for (var i = 0; i < color.length; i++) {
if (color.charAt(i) == ",") {
counter++;
endIndex = i;
}
if (counter == 4) {
stringHolder = color.substring(startIndex, endIndex);
alert(stringHolder);
newString = color.substring(endIndex+1, color.length);
getEachColorValue(stringHolder);
colorSetHT.push(firstC, secondC, thirdC)
colorReset();
counter = 0;
stringHolder = "";
// createSubstring(newString); // ?
}
}
}
I've tried this, but had no luck so far. I even tried to do it recursively.
Im kinda new to Javascript (actually doing it for Extendscript), I think theres a way easier way, working with split/slice but I havent been able to find one yet. I tried to make it as easy and fast to read as possible, please let me know if I can provide any further information, thanks in advance!
Here is how to do it with split.
var input = "255,255,255,10,251,91,31,4,220,220,220,1";
var inputArray = input.split(",");
var outputArray = [];
for(let i = 0;i<inputArray.length;i++)
{
if(i%4 != 3)
{
outputArray.push(inputArray[i]);
}
}
var output = outputArray.join(",");
console.log(output);
Try
let output = input.split(',').filter((x,i)=> i%4-3).join();
let input="255,255,255,10,251,91,31,4,220,220,220,1"
let output = input.split(',').filter((x,i)=> i%4-3).join();
console.log(output);
Use a simple for loop like so:
const str = "255,255,255,10,251,91,31,4,220,220,220,1";
var colors = str.split(",");
var x = Math.floor(colours.length / 4);
while (x--) {
colors.splice((x + 1) * 4 - 1, 1);
}
colors = colors.join(",");
console.log(colors);

Inserting a Value without splice or push command

I am currently working on some code to insert user inputted variables into an array at a specified point WITHOUT using the splice or the push command. I decided to try to use a while command as that is what makes the most sense to me as I am very new to javascript. When I do try to display nothing comes up.
var array = []; // Flobal array to hold array
var d = ""; // Global string for output
function fillArray() {
// call function to clear the display values
clearDisplay();
// simple loop hard coded to 100 to set array values
for (var i = 0; i < 100; i++) {
array[i] = Math.floor(Math.random() * 100 + 1);
}
// call function to display the array
displayArray();
}
function clearDisplay() {
//Global string d is used to hold display
d = "";
// The div element named output is used to display output
document.getElementById("output").innerHTML = "";
}
function displayArray() {
// simple loop to add array values to string d
for (var i = 0; i < array.length - 1; i++) {
d += i + ' : ' + array[i] + "<br/>";
}
document.getElementById("output").innerHTML = d;
}
//-------------------------------------------------------
//Scan array and insert into index
function insertArray() {
var m = parseInt(document.getElementById("index").value);
var n = parseInt(document.getElementById("value").value);
while (i < m) {
i++;
}
if (i == m) {
array[i] == n;
}
displayArray();
}
Possible solution is to create new array every time and overwrite old one. We create two counters one for old array, second for new array. While coping items from old array to new one, when we'r at desired index we'r adding desired value from input and increases only new array counter.
function insertArray() {
var m = parseInt(document.getElementById("index").value);
var n = parseInt(document.getElementById("value").value);
var c = 0, o = 0, l = array.length + 1, new_array = [];
while (c < l) {
if (c === m) {
new_array[c] = n;
} else {
new_array[c] = array[o];
o++;
}
c++;
}
array = new_array;
clearDisplay();
displayArray();
}
var array = []; // Flobal array to hold array
var d = ""; // Global string for output
function fillArray() {
// call function to clear the display values
clearDisplay();
// simple loop hard coded to 10 to set array values
for (var i = 0; i < 10; i++) {
array[i] = Math.floor(Math.random() * 100 + 1);
}
// call function to display the array
displayArray();
}
function clearDisplay() {
//Global string d is used to hold display
d = "";
// The div element named output is used to display output
document.getElementById("output").innerHTML = "";
}
function displayArray() {
// simple loop to add array values to string d
for (var i = 0; i < array.length; i++) {
d += i + " : " + array[i] + "<br/>";
}
document.getElementById("output").innerHTML = d;
}
fillArray();
//-------------------------------------------------------
//Scan array and insert into index
function insertArray() {
var m = parseInt(document.getElementById("index").value);
var n = parseInt(document.getElementById("value").value);
var c = 0, o = 0, l = array.length + 1, new_array = [];
while (c < l) {
if (c === m) {
new_array[c] = n;
} else {
new_array[c] = array[o];
o++;
}
c++;
}
array = new_array;
clearDisplay();
displayArray();
}
<p>Output: </p>
<input type="text" id="index">
<input type="text" id="value">
<button onClick="insertArray();">Insert</button>
<hr>
<div id="output">
</div>
You can use the following code to add elements to an array without using the splice or push command at the given index. See the implementation of insertArray function, I have commented out the wrong code and written a new line.
var array = []; // Flobal array to hold array
var d = ""; // Global string for output
function fillArray() {
// call function to clear the display values
clearDisplay();
// simple loop hard coded to 100 to set array values
for (var i = 0; i < 100; i++) {
array[i] = Math.floor(Math.random() * 100 + 1);
}
// call function to display the array
//displayArray();
}
function clearDisplay() {
//Global string d is used to hold display
d = "";
// The div element named output is used to display output
document.getElementById("output").innerHTML = "";
}
function displayArray() {
// simple loop to add array values to string d
for (var i = 0; i < array.length - 1; i++) {
d += i + ' : ' + array[i] + " ";
}
document.getElementById("output").innerHTML = d;
}
//-------------------------------------------------------
//Scan array and insert into index
function insertArray() {
var m = parseInt(document.getElementById("index").value);
var n = parseInt(document.getElementById("value").value);
var temp = array[m];
array[m] = n;
for (var i = m+1; i < 100; i++) {
array[i] = temp;
temp = array[i];
}
/*
while (i < m) {
i++;
}
if (i == m) {
array[i] = n;
}
*/
displayArray();
}
fillArray();
<p>Output: </p>
<input type="text" id="index">
<input type="text" id="value">
<button onClick="insertArray();">Insert</button>
<hr>
<div id="output">
</div>
Please let me know if this is what you wanted.

How to display output of one function after another

I have written a Javascript file of two algorithms. As shown in the code below, I am using a for loop to generate random values which are used by both algorithms as input.
At present, I am displaying output of the binarySearch and SearchSorted alternatively.
The problem I am facing is I have to pass the same array values generated by randomlyGenerateArray in the main program to both the algorithms for a meaningful comparison. But I don't know how to change the output format.
I have thought of adding them in different loops, but as I have explained above i need to use the same randomArray values for both the algorithms.
i.e., The below code produces output as shown below -
Binary Search Successful 1
Search Sorted Successful 5
Binary Search Successful 3
Search Sorted Successful 10
How do I display the output of Binary Search First and then display output of Search Sorted? it's something like this. Any help will be greatly appreciated.
Binary Search Successful 1
Binary Search Successful 3
Search Sorted Successful 5
Search Sorted Successful 10
// Binary Search Algorithm
function binarySearch(A,K)
{
var l = 0; // min
var r = A.length - 1; //max
var n = A.length;
var operations = 0;
while(l <= r)
{
var m = Math.floor((l + r)/2);
operations++;
if(K == A[m])
{
console.log('Binary Search Successful %d',operations);
return m;
}
else if(K < A[m])
{
r = m - 1;
}
else
{
l = m + 1;
}
}
operations++;
console.log('Binary Search Unsuccessful %d',operations);
return -1;
}
// Search Sorted Algorithm
function searchSorted(A, K)
{
var n = A.length;
var i = 0;
var operations = 0;
while (i < n)
{
operations++;
if (K < A[i])
{
return -1;
}
else if (K == A[i])
{
console.log('Search Sorted Successful %d', operations);
return i;
}
else
{
i = i + 1;
}
}
operations++;
console.log('Search Sorted Unsuccessful %d', operations);
return -1;
}
// Random Array generator
var randomlyGenerateArray = function(size)
{
var array = [];
for (var i = 0; i < size; i++)
{
var temp = Math.floor(Math.random() * maxArrayValue);
var final = array.splice(5, 0, 30);
array.push(final);
}
return array;
}
//Sort the Array
var sortNumber = function(a, b)
{
return a - b;
}
// Main Program
var program = function()
{
var incrementSize = largestArray / numberOfArrays;
for (var i = smallestArray; i <= largestArray; i += incrementSize)
{
var randomArray = randomlyGenerateArray(i);
var sort = randomArray.sort(sortNumber);
var randomKey = 30;
binarySearch(sort, randomKey);
searchSorted(sort, randomKey);
}
}
var smallestArray = 10;
var largestArray = 10000;
var numberOfArrays = 1000;
var minArrayValue = 1;
var maxArrayValue = 1000;
program();
You could store the sorted randomArrays in an array (which I've called sortedRandomArrays), then run a for loop for each search.
The Main Program would then look like:
// Main Program
var program = function()
{
var incrementSize = largestArray / numberOfArrays;
var sortedRandomArrays = [];
for (var i = smallestArray; i <= largestArray; i += incrementSize)
{
var randomArray = randomlyGenerateArray(i));
var sort = randomArray.sort(sortNumber);
sortedRandomArrays.push(sort);
var randomKey = 30;
}
for (var i = 0; i < sortedRandomArrays.length; i++)
{
binarySearch(sortedRandomArrays[i], randomKey);
}
for (var i = 0; i < sortedRandomArrays.length; i++)
{
searchSorted(sortedRandomArrays[i], randomKey);
}
}
Solution is simple: store the results and print with 2 separate loops (take out the printing from within the functions).
var program = function()
{
var binarySearchResults = [];
var sortedSearchResults = [];
var incrementSize = largestArray / numberOfArrays;
for (var i = smallestArray; i <= largestArray; i += incrementSize)
{
var randomArray = randomlyGenerateArray(i);
var sort = randomArray.sort(sortNumber);
var randomKey = 30;
binarySearchResults[i] = binarySearch(sort, randomKey);
sortedSearchResults[i] = searchSorted(sort, randomKey);
}
for (var i = smallestArray; i <= largestArray; i += incrementSize)
{
//print binary results
}
for (var i = smallestArray; i <= largestArray; i += incrementSize)
{
//print sorted results
}
}

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));

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

Categories