Solució Triangle bonic
De wikiserver
var c = ' ';
result="";
for (i=1; i<=10; i++){
// escriure el caracters buits
for(j=1; j<=10-i; j++){
result = result + c;
}
// escriure la seqüència creixent
var n = i;
for(j=1; j<=i;j++){
if(n == 10) n = 0;
result = result + n;
n++;
}
// escriure la seqüència decreixent
n = n-2;
for (j=1; j<=i-1; j++){
if(n == -1) n =9;
result = result + n;
n--;
}
result = result + "<br>";
}
document.write(result);
Una altre solució sense bucles:
var alfa = ["","1","2","3","4","5","6","7","8","9","0"];
console.log(alfa.reduce(function(data, item, index){
var b = alfa.reduce(function(linea, item2, index2){
//espais en blanc
if (index2 > index)
linea["blancs"] = linea["blancs"] + " ";
//cadena ascendent
if((index > (index2 - index)) & index <= index2 )
linea["asc"] = linea["asc"] + item2;
//cadena descenc¡dent
if((index > (index2 - index)+1) & index <= index2 )
linea["desc"] = item2 + linea["desc"];
//part del mig
var n = alfa.length / 2;
if (index > n)
{
//cadena del mig ascendent
if(index2 <= index - (alfa.length - index)){
linea["medasc"] = linea["medasc"] + item2;
}
//cadena del mig descendent
if(index2 < index - (alfa.length - index)){
linea["meddesc"] = item2 + linea["meddesc"];
}
}
return linea;
},{blancs: "", asc:"", desc:"", medasc:"", meddesc:""});
data.push(b["blancs"] + b["asc"] + b["medasc"] + b["meddesc"] + b["desc"]+"\n");
return data;
},[]));