Home >Web Front-end >JS Tutorial >JavaScript builds a string pyramid

JavaScript builds a string pyramid

黄舟
黄舟Original
2017-02-15 14:52:171731browse

I encountered a very interesting topic today. I used JS to construct a pyramid graphic composed of strings. I personally feel that such a topic is very helpful for exercising logical thinking and applying basic knowledge. I would like to share it with you here. Share it with everyone.

First, paste the running results. You will quickly find that this is the result of observing the pyramid from the side and above, and also counts the number of stones (characters) used.

The code is composed of four functions, which can be passed in any string. Construct

//从侧面看金字塔
		function watchPyramidFromTheSide(characters) {
			var str = "";
			for(var i=characters.length-1;i>=0;i--){
				for(var j=0;j<i;j++){
					str += " ";
				}
				var num = 2 * characters.length - 1 - j * 2;
				for(j=0;j<num;j++){
					str += characters.charAt(i);
				}
				for(j=0;j<i;j++){
					str += " ";
				}
				if(i>0){
					str += "\n";
				}
			}
			return str;
		}
		
		//从上方看金字塔
		function watchPyramidFromAbove(characters) {
			var matrix = [];
			var str = "";
			//边最长为
			var sideLongest = characters.length * 2 - 1;
			for(var i=0;i<characters.length;i++){
				var chr = characters.charAt(i);
				for(var j=i;j<sideLongest-i;j++){
					if(!matrix[j]){
						matrix[j] = new Array(sideLongest);
					}
					for(var k=i;k<sideLongest-i;k++){
						matrix[j][k] = chr;
					}
				}
			}
			//组合字符串
			for(i=0;i<matrix.length;i++){
				str += matrix[i].join("");
				if(i<matrix.length-1){
					str += "\n";
				}
			}
			return str;
		}
		
		//能看到的金字塔字符数
		function countVisibleCharactersOfThePyramid(characters) {
			return Math.pow(characters.length * 2 - 1,2);
		}
		
		//金字塔总字符数
		function countAllCharactersOfThePyramid(characters) {
			var len = characters.length;
			var count = 0;
			while(len >= 1){
				count += Math.pow(2 * len - 1,2);
				len--;
			}
			return count;
		}

The above is the content of JavaScript to construct a string pyramid. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn