Create Javascript array with Javascript for loop - javascript

I have a series of information that I am looking to cut down to size by looping the information. Here is the original code that is working:
$('#M1s1').css({'visibility': M1s1v});
$('#M1s2').css({'visibility': M1s2v});
$('#M1s3').css({'visibility': M1s3v});
$('#M1s4').css({'visibility': M1s4v});
$('#M1s5').css({'visibility': M1s5v});
$('#M1s6').css({'visibility': M1s6v});
$('#M1s7').css({'visibility': M1s7v});
$('#M2s1').css({'visibility': M2s1v});
$('#M2s2').css({'visibility': M2s2v});
$('#M2s3').css({'visibility': M2s3v});
$('#M2s4').css({'visibility': M2s4v});
$('#M2s5').css({'visibility': M2s5v});
$('#M2s6').css({'visibility': M2s6v});
$('#M2s7').css({'visibility': M2s7v});
$('#M3s1').css({'visibility': M3s1v});
$('#M3s2').css({'visibility': M3s2v});
$('#M3s3').css({'visibility': M3s3v});
$('#M3s4').css({'visibility': M3s4v});
$('#M3s5').css({'visibility': M3s5v});
$('#M3s6').css({'visibility': M3s6v});
$('#M3s7').css({'visibility': M3s7v});
$('#M4s1').css({'visibility': M4s1v});
$('#M4s2').css({'visibility': M4s2v});
$('#M4s3').css({'visibility': M4s3v});
$('#M4s4').css({'visibility': M4s4v});
$('#M4s5').css({'visibility': M4s5v});
$('#M4s6').css({'visibility': M4s6v});
$('#M4s7').css({'visibility': M4s7v});
$('#M5s1').css({'visibility': M5s1v});
$('#M5s2').css({'visibility': M5s2v});
$('#M5s3').css({'visibility': M5s3v});
$('#M5s4').css({'visibility': M5s4v});
$('#M5s5').css({'visibility': M5s5v});
$('#M5s6').css({'visibility': M5s6v});
$('#M5s7').css({'visibility': M5s7v});
And here is the for loops that I created to try and cut down the length of code and possibility of typing errors:
// set smc array(#M1s1, #M1s2, #M1s3, etc.)
var smc = [];
for (m = 1; m < 6; m++) {
for (s = 1; s < 8; s++) {
var smc[] = '#M' + m + 's' + s;
}
}
// set smcv array(#M1s1v, #M1s2v, #M1s3v, etc.)
var smcv = [];
for (mv = 1; mv < 6; mv++) {
for (sv = 1; sv < 8; sv++) {
var smcv[] = '#M' + mv + 's' + sv + 'v';
}
}
// loop to set visibility of small circles
for (i = 0; i < 35; i++) {
$(smc[i]).css({'visibility': smcv[i]});
}
I am really new to javascript loops and feel like I may be overlooking something basic or even a syntax error of some kind but can't put a finger on what the problem is. Any direction or assistance would be greatly appreciated!
UPDATE
Here is the final solution to my problem:
//set smc array(#M1s1, #M1s2, #M1s3, etc.)
var smc = [];
for (m = 1; m < 6; m++) {
for (s = 1; s < 8; s++) {
smc.push('#M' + m + 's' + s);
}
}
//set smcv array(#Ms1v, #M1s2v, #M1s3v, etc.)
var smcv = [];
for (mv = 1; mv < 6; mv++) {
for (sv = 1; sv < 8; sv++) {
smcv.push('M' + mv + 's' + sv + 'v');
}
}
//loop to set visibility of small circles
for (i = 0; i < 35; i++) {
$(smc[i]).css({'visibility': window[smcv[i]]});
}

You can't push value to array using var smc[] = 'something'.
Use smc.push( 'something' )

Lets say the M1s1v,M1s2v,.... values are coming from a json variable, something like this:
var x = {
M1s1v : "hidden",
M1s2v : "visibile",
...
}
then you can cut-short the code to something like this:
for (m = 1; m < 6; m++) {
for (s = 1; s < 8; s++) {
$('#M' + m + 's' + s).css({'visiblity':x['M'+m+'s'+s+'v']});
}
}
Hope it helps.

Say you have a two dimensional array, 5 x 7 for M and s holding something that will evaluate to true/false (boolean, 0, 1, empty string...).
var data = [][];
...
for (var M=0; M < data.length; M++) {
for (var s=0; s < data[M].length; M++) {
$('#M' + (M+1) + 's' + (s+1)).css({'visibility': data[M][s] ? 'visible' : 'hidden'});
}
}
You could "optimize" by using hard coded numbers instead of the lengths if you were centian of the dimensions.

Related

How to write a number pattern generator program in JavaScript?

I have to make a pattern like this:
=========1=========
=======22122=======
====33322122333====
4444333221223334444
I have not found the logic yet. I tried to code it, but the output is different.
Here is the output of my working code snippet:
----1-----
---123----
--12345---
-1234567--
123456789-
function nomor3(input){
let temp = '';
for (let x = 1; x <= input; x++){
for (let y = input ; y > x; y--){
temp += "-";
}
for (let z = 1; z <= (x * 2) - 1; z++){
temp += z;
}
for (let k = input; k >= x; k--){
temp += "-";
}
temp += '\n';
}
return temp
}
console.log(nomor3(5));
The logic for each level - say 4th level - it begins with the digit of the level to the count of the digit, then one less and so on. So line 4 looks like 4444-333-22-1 and backwards (dashes added for demonstration).
So here we build each line like that, starting from the biggest so we know its length so we can center other lines with dashes. We use arrays here and reversing them because it's easier than strings. But lastly we join so we have a string.
function pyramide(level) {
var len = null;
var result = [];
while (level > 0) {
var arr = [];
for (var i = level; i > 1; i--) {
for (var repeat = 0; repeat < i; repeat++) {
arr.push(i)
}
}
var str_level = arr.join("") + "1" + arr.reverse().join("");
if (len === null) {
len = str_level.length;
}
while (str_level.length < len) {
str_level = "-" + str_level + "-";
}
result.push(str_level);
level--;
}
return result.reverse().join("\n");
}
console.log(pyramide(5))

How to print basic Christmas Tree with JavaScript?

Trying to make a simple script that draws a tree of certain height in console with simple JS loops. It should look like that.
For height = 4 :
*
***
*****
*******
so far have this but somehow it's not working:
function drawTree(height) {
for ( var i = 0; i < height ; i++ ) {
var star = '*';
var space = ' ';
for ( var j = 1; j <= i; j++ ) {
star = star + '***';
}
for ( var k = height - 1 ; k > 0; k-- ) {
spacesBefore = space.repeat(k);
star = spacesBefore + star;
}
console.log(star);
}
}
var levels = prompt('How many levels high should be the tree?');
drawTree(levels);
alert('Check console')
any advice where I'm wrong? thx <3
You had 2 minor problems with your code.
There should be an odd number of stars per level (1, 3, 5, 7, ...) and you were adding 3n + 1 stars which will alternate between even and odd. The change to make for that is star = star + "**" instead of ... + "***"
There is no need for the for (var k = ...) loop for counting the spaces. Your logic is right, but looping over the entire height for each row will yield you the same number of spaces per row, which is what your output is showing, which is wrong. What you want to do instead for the number of spaces is height - i - 1.
A working solution would look like the following:
function drawTree(height) {
for ( var i = 0; i < height ; i++ ) {
var star = '*';
var space = ' ';
for ( var j = 1; j <= i; j++ ) {
star = star + '**';
}
var spacesBefore = space.repeat(height-i-1);
star = spacesBefore + star;
console.log(star);
}
}
var levels = prompt('How many levels high should be the tree?');
drawTree(levels);
A more concise version of this code would look like the following:
function drawTree(height) {
for (var i = 0; i < height; i++) {
// 2n+1 stars per row i.e. 1, 3, 5, 7, ...
var stars = '*'.repeat(2 * i + 1);
var spacesBefore = ' '.repeat(height - i - 1);
console.log(spacesBefore + stars);
}
}
drawTree(prompt('How many levels high should be the tree?'));
Would like to calculate width first and then use that width. Spaces are depended upon width and number of * in each height.
width = height*2 - 1;
Code for tree:
function tree(h) {
let i =0, j = 1;
w = h*2 - 1;
let space = parseInt(w / 2);
while (space >= 0) {
let str = '';
for (i = 0; i < space; i++) str += ' ';
for (i = 0; i<j; i++) str += '*';
console.log(str);
// Since every next line got 2 more *
j += 2;
// Number of space reduce by 1
space--;
}
}
function drawTree(h) {
let star = "*";
let space = " ";
let spaceCount = h-1;
let starCount = 1;
for(let i = 0; i < h; i++) {
console.log(`${space.repeat(spaceCount)}${star.repeat(starCount)}${space.repeat(spaceCount)}`);
spaceCount -= 1;
starCount += 2;
}
}
drawTree(20)

Simple Javascript Christmas Tree

I created a half of the Christmas Tree but here I got blocked. Some one please help me to understand how to do the left side too.
for (var i = 0; i < 8; i++) {
for (var j = 0; j <= i; j++) {
document.write("^");
}
document.write("<br>");
}
<pre>
<script>
//Reads number of rows to be printed
var n = 8;
for(i=1; i<=n; i++)
{
//Prints trailing spaces
for(j=i; j<n; j++)
{
document.write(" ");
}
//Prints the pyramid pattern
for(j=1; j<=(2*i-1); j++)
{
document.write("*");
}
document.write("<br>");
}
</script>
</pre>
Source: http://codeforwin.org/2015/07/equilateral-triangle-star-pattern-program-in-c.html
C to JavaScript by me.
I wrote the following code for this problem.
I also added a nice extra, christmas-tree ornaments :-)
import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone
{
private static Random RND = new Random(System.currentTimeMillis()); // useful for placing balls
private static char[] BALLS = {'o','⌾','⛣','⏣','◍'}; // symbols being used as balls
public static void main (String[] args) throws java.lang.Exception
{
int w = 27; // width of the tree
int b = 10; // number of balls in the tree
String tree = ""; // this will end up containing the tree
// build tree
w = ( w % 2 == 1 ) ? w : 13; // check whether width is odd
for(int i=1;i<=w;i+=2){
int s = (w - i) / 2;
tree += repeat(' ', s) + repeat('*', i) + repeat(' ', s) + "\n";
}
// randomly replace some parts by balls
int i=0;
while(i < b){
int j = RND.nextInt(tree.length());
if(tree.charAt(j) == '*'){
tree = tree.substring(0, j) + BALLS[RND.nextInt(BALLS.length)] + tree.substring(j+1);
i++;
}
}
// build trunk
tree += repeat(' ', (w - 4) / 2) + repeat('*', 4) + "\n" + repeat(' ', (w - 4) / 2) + repeat('*', 4);
// output
System.out.println(tree);
}
// this function builds a String by repeating a given character a couple of times
private static String repeat(char c, int l){
String s = "";
for(int i=0;i<l;i++)
s += c;
return s;
}
}
The output should look something like this:
⏣
***
*o***
**⌾*o**
*****⛣**⛣
*****⌾****⏣
**◍*◍********
****
****
The keyword is think.
var x = 8;
for (let i = 0; i < x; i++) {
for (let j=x-1; j>i; j--) {
document.write("&nbsp&nbsp");
}
for (let k=0; k<=(i*2); k++) {
document.write("^");
}
document.write("<br>");
}
for (let i=0; i<2; i++) {
for (let j=0; j<(x*2)-3; j++) {
document.write("&nbsp");
}
document.write("^<br>");
}
Constraints: Only looks good starting from x = 5.
Original code by me
The answers above heavily rely on nested loops, thought I post another approach with "modern" JS (of course still using a single loop with the map function given to Array.from()):
function xmas(height) {
// add 1 more level for the trunk, e.g. height+1
return Array.from({length: height+1}, (v, i) => {
return i === height
// that's for the trunk of the tree
? '*'.padStart(Math.round((2 * i)/2), ' ')
// the actual tree "levels"
: '*'.repeat(2 * i + 1).padStart(2 * i + height-i, ' ');
}).join('\n');
}
document.write(`<pre>${xmas(10)}</pre>`);
maybe the attempt to make it work with .padStart() is not optimal because the math gets a bit ugly, but anyways, just for fun =)...
Here's a solution with a simple for loop without any nested loop.
let row = ""
let l = 9
for (let i = 0; i < l; i++) {
row += " ".repeat(l - i) + "*" + "*".repeat(i * 2) + `\n`;
}
console.log(row);
Simple christmas tree function:
function christmasTree(x) {
if(x < 3) {
return "";
}
let tree = "";
for(let i = 1; i <= x; i++) {
for(let j = 1; j <= x + x - 1; j++) {
if(j <= x - i || j >= x + i) {
tree += " ";
} else {
tree += "*";
}
}
tree += "\n";
}
return tree;
}
Incase you are looking for how to do this in a function for javascript or typescript
Use 3 for loops,
1 - Number of rows
2 - Number of spaces
3 - Number of characters
function christmas(n) {
let tree = '';
for (let i = 1; i <= n; i++) {
for (let j=0; j <= n-i; j++) {
tree += ' ';
}
for (k = 0; k< (i*2)-1; k++) {
tree += '*';
}
tree += '\n';
}
return tree;
}
console.log(christmas(3));
<pre>
<script>
//Reads number of rows to be printed
var n = 8;
for(i=1; i<=n; i++)
{
//Prints trailing spaces
for(j=i; j<n; j++)
{
document.write(" ");
}
//Prints the pyramid pattern
for(j=1; j<=(2*i-1); j++)
{
document.write("*");
}
document.write("<br>");
}
</script>
</pre>

Javascript - String matching wrong output

I have coded Boyer-Moore horspool string matching algorithm using node.js. The program works, but always outputs -1, which is what it should output if the pattern string is not in the specified text.
I am unable to figure out for the life of me what isn't working, and I would be most appreciative of a hint for what I need to fix.
My code
var horsPool = function(sText,sPattern)
{
var m = sPattern.length;
var n = sText.length;
var i = m - 1;
while(i<=n-1)
{
var k = 0;
while ((k <= m) && (sPattern[m - 1 - k]) == sText[i - k])
{
k++;
}
if(k==m)
{
return (i - m + 1);
}
else
{
i += t[sText[i]];
}
}
return -1;
}
var shiftTable = function (sPat)
{
var i;
var j;
var m;
m = sPat.length;
for(i=0; i < MAX; i++)
{
t[i] = m;
}
for (j = 0; j<m-2; j++)
{
t[sPat[j]] = m-1 -j;
}
}
var program = function()
{
var text = 'lklkababcabab';
var pattern = 'ka';
shiftTable(pattern);
var pos = horsPool(text,pattern);
if(pos >= 0)
console.log('Pattern found in %d',pos);
else
console.log('Pattern not found');
}
var MAX = new Array(256);
var t = [MAX];
program();
Any help would be greatly appreciated. Thank You!
Let's start from down under:
var MAX = new Array(256);
var t = [MAX];
does not work at all. The first line initiates an array with 256 empty entries, the second line initiates an array with one element: the array build in the line above. That's not what you wanted to do, I presume. So
var MAX = 256;
var t = new Array(MAX);
does what you want.
The lines with t[sPat[j]] and t[sText[i]] will not work as expected, because sText[i] and sPat[j] return a character instead of a number. You might give t[sPat.charCodeAt(j)] and t[sText.charCodeAt(i)] a try.
To give you a start without helping too much, here is a straight-forward implementation of the algorithm given at Wikipedia:
var horsPool = function (haystack, needle)
{
var nl = needle.length;
var hl = haystack.length;
var skip = 0;
while (hl - skip >= nl)
{
var i = nl - 1;
while (haystack[skip + i] == needle[i])
{
if (i == 0) {
return skip;
}
i--;
}
skip = skip + t[haystack.charCodeAt(skip + nl - 1)];
}
return - 1;
}
var shiftTable = function (pattern)
{
for (var i = 0; i < MAX; i++) {
t[i] = pattern.length;
}
for (var i = 0; i < pattern.length - 1; i++) {
t[pattern.charCodeAt(i)] = pattern.length - 1 - i;
}
}
var program = function ()
{
var text = 'lklkababcabab';
var pattern = 'kab';
shiftTable(pattern);
var pos = horsPool(text, pattern);
if (pos >= 0)
console.log('Pattern found in %d', pos);
else
console.log('Pattern not found');
}
var MAX = 256;
var t = new Array(256);
program();

Generating alphanumerical sequence javascript

I have written a terribly slow function for generating codes that go from AA000 to ZZ999 (in sequence not random). And I have concluded that there has to be a better way to do this. Any suggestions on how to make this faster?
function generateAlphaNumeric(){
theAlphabet = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
resultArrray = [];
resultArrray2 = [];
teller = 0;
for(i in theAlphabet){
for(x in theAlphabet){
resultArrray[teller] = theAlphabet[i] + theAlphabet[x];
teller++;
}
}
teller = 0;
for(x = 0; x<10; x++){
for(y = 0; y<10; y++){
for(z = 0; z<10; z++){
resultArrray2[teller] = x.toString() + y.toString() +z.toString();
teller++;
}
}
}
teller = 0;
finalArray = [];
for(index in resultArrray){
for(i in resultArrray2){
finalArray[teller] = resultArrray[index] + resultArrray2[i];
teller++;
}
}
//console.log(resultArrray);
//console.log(resultArrray2);
console.log(finalArray);
}
This should be considerably faster:
var theAlphabet = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O',
'P','Q','R','S','T','U','V','W','X','Y','Z'];
var theDigits = ['0','1','2','3','4','5','6','7','8','9'];
var result = [];
for (var i=0 ; i<26 ; i++) {
var prefix1 = theAlphabet[i];
for (var j=0 ; j<26; j++) {
var prefix2 = prefix1 + theAlphabet[j];
for(var x = 0; x<10; x++){
var prefix3 = prefix2 + theDigits[x];
for(var y = 0; y<10; y++){
var prefix4 = prefix3 + theDigits[y];
for(var z = 0; z<10; z++){
result.push(prefix4 + theDigits[z]);
}
}
}
}
}
Key ideas:
Generate everything in one run
Reuse partial strings as much as possible
However, I don't see how such an exhaustive list is useful. There are exactly 26 * 26 * 1000 different codes. So instead of maintaining an array with all codes it could make sense to simply build a function that generates the specific code requested:
function getCode(number) {
var z = number % 10;
number -= z; number /= 10;
var y = number % 10;
number -= y; number /= 10;
var x = number % 10;
number -= x; number /= 10;
var a = number % 26;
number -= a; number /= 26;
var b = number;
return theAlphabet[a] + theAlphabet[b] + theDigits[x] + theDigits[y] + theDigits[z];
}
function generate() {
var str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
array = [];
for (var i = 0; i < str.length; i++) {
for (var j = 0; j < str.length; j++) {
for (var k = 0; k < 10; k++) {
for (var l = 0; l < 10; l++) {
for (var m = 0; m < 10; m++) {
ar.push(str[i] + str[j] + k + l + m);
}
}
}
}
}
return array;
}
console.log(generate());
This will generate a array of all the codes .. U can save that array and parse it easily using a loop.
Try this solution:
function generate() {
var str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
ar = [];
for (var index1 = 0; index1 < str.length; index1++) {
for (var index2 = 0; index2 < str.length; index2++) {
for (var index3 = 0; index3 < 1000; index3++) {
ar.push(str[index1] + str[index2] + ('000' + index3).slice(-3));
}
}
}
return ar;
}
console.log(generate());
I didn't test it, but it should do the trick
function generateAlphaNumeric()
{
var theAlphabet = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
var result = [];
// Will take a random letter inside theAlphabet
// Math.floor(Math.random() * theAlphabet.length) will generate a random number between 0 and 25
var i = 0;
while(i<2)
{
var letter = theAlphabet[Math.floor(Math.random() * theAlphabet.length)];
result.push(letter);
i++;
}
i = 0;
while(i<3)
{
// Adds a random number between 0 and 9
result.push(Math.floor(Math.random() * 10));
i++;
}
return result;
}
From a computational complexity perspective, unfortunately this is the best you can do. From a sheer number of instructions perspective, you can do a bit better (as others have pointed out), but it's still going to be the same order of complexity (remember that constants / multipliers are irrelevant in big-O complexity). You can also optimize the storage a bit.
Think about it. Your array needs to have 26 * 26 * 10 * 10 * 10 members. This means you need to at least touch that many elements.
Let N = number of elements in the alphabet
Let M = number of elements in your digit queue
Best Case Order Complexity = O(N * N * M * M * M) (if all you had to do was assign values)
Best case storage complexity = same as above (you have to store all the codes)
Right now you are using the following operations:
for(i in theAlphabet){ // *O(N)*
for(x in theAlphabet){ // *O(N)*
resultArrray[teller] = theAlphabet[i] + theAlphabet[x];// *(O(1))*
}
}
for(x = 0; x<10; x++){ // O(M)
for(y = 0; y<10; y++){ // O(M)
for(z = 0; z<10; z++){ // O(M)
resultArrray2[teller] = x.toString() + y.toString() +z.toString(); // O(1) (technically this is O(length of x + y + z)
teller++;
}
}
}
for(index in resultArrray){ // O(N * N)
for(i in resultArrray2){ // O(M * M * M(
finalArray[teller] = resultArrray[index] + resultArrray2[i]; //O(1)
teller++;
}
}
So at the end of the day your order complexity is O(N * N * M * M * M), which is the best you can do.
The bigger question is why you want to generate all the codes at all. If all you want is to create a unique code per order number or something, you can make a state machine like:
function getNextCode(previousCode) {
// in here, just increment the previous code
}
If all you want is a random identifier, consider using a hash of the timestamp + something about the request instead.
If you don't care about uniqueness, you can always just generate a random code.
All of the above are O(1).

Categories

Resources