Hola tengo un problema. Quiero crear un patrón numérico triangular de la siguiente manera:
Output: 1223334444333221 =22333444433322= ===3334444333=== ======4444======He intentado hacer el programa. Pero la lógica que uso no es del todo correcta.
function nomor4(level) { let len = null; let result = []; while (level > 0) { let arr = []; for (let i = 1; i < level; i++) { for (let repeat = 0; repeat <i; repeat++){ arr.push(i) } } // convert arr.push value from array to string using join //and add 1 and the copy value using reverse let str_level = arr.join("") + "4444" + arr.reverse().join(""); if (len == null) { len = str_level.length; } //Add Strip while (str_level.length < len) { str_level = "-" + str_level + "-"; } result.push(str_level); level--; } return result.join("\n"); } console.log(nomor4(4))si alguien puede por favor ayúdame a dar la solución. Gracias
Aquí hay una forma de hacer esto usando dos mapas anidados sobre arreglos de filas (un contador para cada fila) y columnas (los valores para imprimir en cada fila)
const size = 4 const fill = '=' const rows = Array.from({length: size}, (_, i) => i + 1) // 1,2,3,4 const cols = rows.concat(rows.slice(0, -1).reverse()) // 1,2,3,4,3,2,1 const result = rows .map(r => cols .map(c => ((c >= r) ? c : fill).toString().repeat(c) ).join('') ).join('\n') console.log(result)Hay mejores formas que esta, pero pondré esto aquí solo para mostrar cómo hacerlo con cambios mínimos desde el OP (acabo de cambiar - a = y el ciclo for con i).
function nomor4(level) { let len = null; let result = []; while (level > 0) { let arr = []; for (let i = 5-level; i < 4; i++) { for (let repeat = 0; repeat <i; repeat++){ arr.push(i) } } // convert arr.push value from array to string using join //and add 1 and the copy value using reverse let str_level = arr.join("") + "4444" + arr.reverse().join(""); if (len == null) { len = str_level.length; } //Add Strip while (str_level.length < len) { str_level = "=" + str_level + "="; } result.push(str_level); level--; } return result.join("\n"); } console.log(nomor4(4)) function nomor4(level) { let realValue = level; let len = null; let result = []; while (level >= 0) { let arr = []; for (let i = 1; i <= realValue; i++) { if (realValue !== i) { for (let repeat = 0; repeat < i; repeat++) { if (realValue - level <= i) { arr.push(i); } } } } // convert arr.push value from array to string using join // and add 1 and the copy value using reverse let str_level = arr.join("") + "4444" + arr.reverse().join(""); if (len == null) { len = str_level.length; } //Add Strip while (str_level.length < len) { str_level = "-" + str_level + "-"; } result.push(str_level); result = [...new Set(result)]; level--; } return result.join("\n"); } console.log(nomor4(4));