bash Linux shell 脚本中的帕斯卡三角形

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33290818/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 13:47:17  来源:igfitidea点击:

Pascal's triangle in Linux shell script

linuxbashshellpascals-triangle

提问by N.john

I'm trying to write a code which receives an integer "n" as a parameter and then print the n-th row of the Pascal's triangle starting from 0, 1,..,n. for example if the entry is 3, the program prints 1 3 3 1. So far I wrote a code to get the whole triangle printed, but I can't have just the last row. This is what I have

我正在尝试编写一个代码,它接收一个整数“n”作为参数,然后打印从 0、1、...、n 开始的 Pascal 三角形的第 n 行。例如,如果条目是 3,程序将打印 1 3 3 1。到目前为止,我编写了一个代码来打印整个三角形,但我不能只打印最后一行。这就是我所拥有的

echo "Insert the row:" read n for((i=0;i<$n;i++)) 
do      
eval"a$i=($(w=1;v=1
        for((j=0;j<$n-$i;j++))
        do 
            [ $i -eq 0 -o $j -eq 0 ]&&{ v=1 && w=1; }||v=$((w+a$((i-1))[$((j))]))
            echo -n "$v "
            w=$v
        done))"
     eval echo "$(for((k=0;k<=$i;k++)) 
        do 
            eval "echo -n \"$((a$((i-k))[k])) \"" 
        done)" 
    done

回答by V. Michel

#!/bin/bash
read -p "Insert the row:"  n

typeset -A Tab

for((i=0;i<=$n;i++))
do
  Tab[$i,0]=1
  Tab[$i,$i]=1
  for((j=1;j<$i;j++))
  do
    a=${Tab[$((i-1)),$((j-1))]}
    b=${Tab[$((i-1)),$j]}
    Tab[$i,$j]=$(( a + b ))
  done
done

#print result
for((j=0;j<=$n;j++))
do
  echo -n ${Tab[$n,$j]} " "
done
echo

Test :

测试 :

Insert the row:3
1  3  3  1 

回答by Yaron

I found an awksolution to that question:

我找到了awk这个问题的解决方案:

awk -v line_num=5 'BEGIN{for(i=line_num;i<=line_num;i++){c=1;r=c;for(j=0;j<i;j++){c*=(i-j)/(j+1);r=r" "c};print r}}'

Change line_numvalue to the desired one.

line_num值更改为所需的值。

Based on a solution found here.

基于此处找到的解决方案。

That's of course if awkcounts…

当然,如果awk算的话……

回答by Muhammad Hassan

Here is a simple bash script to print pascal's triangle using simple for,if else and echo command:

这是一个简单的 bash 脚本,用于使用简单的 for,if else 和 echo 命令打印帕斯卡的三角形:

echo "Enter number of rows : "
read rows
coef=1
for((i=0;i<rows;i++))
do
  for((space=1;space<=rows-i; space++))
  do
    echo -n "  "
  done
  for((j=0;j<=i;j++))
  do
    if [ $j -eq 0 -o $i -eq 0 ]
    then
        coef=1;
    else
        coef=$((coef*(i-j+1)/j))
    fi
    echo -n $coef "   "
  done
  echo
done