【问题标题】:KornShell to generate the number of combinations of k objects from a set with n objectsKornShell 从具有 n 个对象的集合中生成 k 个对象的组合数
【发布时间】:2014-01-27 13:04:58
【问题描述】:

任何人都可以帮助获取使用 KornShell (ksh) 的代码,以从具有 n 个对象的集合中生成 k 个对象的组合数为 n C k 吗? 例如,一次取 k=2 的 {1,2,3,4} 的组合是 {1,2}, {1,3}, {1,4}, {2,3}, {2, 4}, {3,4},总共 6 = 4 / [(2)(4-2) ] 个子集。

【问题讨论】:

  • 为什么选择 ksh? Unix shell 不太擅长这类计算。
  • 是组合的数量(所以是统计评估)还是你想要的所有生成的组合?
  • 这个问题中的符号代表什么?
  • @java请我猜它们在某些平台上呈现为......某些东西,但就像(我猜)你一样,我只是在我的 iPhone 上看到空方块。

标签: algorithm shell math scripting ksh


【解决方案1】:

@Ned Nowotny 是对的,sh 不适合这样做

也就是说,这是递归形式:

> function cr { integer n=$1 k=$2; if ((k==1)); then print $n; elif ((k==n)); then print 1; else print $(($(cr $((n-1)) $((k-1))) + $(($(cr $((n-1)) $k))))); fi; }
> cr 4 2
6
> 

这是更快的阶乘形式:

> function fact { integer x=$1 f=1; while ((x>0)) do : $((f*=x--)); done; print $f; }
> function cf { integer n=$1 k=$2; print $(($(fact $n)/($(fact $k)*$(fact $(($n-$k)))))); }
> cf 4 2
6
> 

【讨论】:

  • 我猜你的意思是$(cr ...)而不是递归形式的$(c ...)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多