使用PowerShell进行无重复组合?

时间:2012-06-27 05:48:09

标签: powershell

我是powershell的新手,但是想知道如何在没有重复的情况下得到给定数字的组合?

例如

$a = (1,2,3,4)
$n = 4
$k = 2

输出: -

12
13
14
23
24
34

如果K = 3那么

123
124
134
234

2 个答案:

答案 0 :(得分:1)

对于那个特定情况来说,只是一个快速的解决方案,我看不出它有多大的价值,因为我觉得有为此类练习设计的工具......;)

$a = (1,2,3,4)

$rest = New-Object Collections.ArrayList
$a[1..($a.Length - 1)] | foreach { $rest.Add($_) | Out-Null }

$prefix = $a[0]

$(while ($rest) {
    foreach ($suffix in $rest) {
        -join ($prefix, $suffix)
    }
    $prefix = $rest[0]
    $rest.RemoveAt(0)
}) -join ', '

答案 1 :(得分:0)

你可以试试这个:

$List = "A","B","C","D","E","F","G","H"
$k = 3

Add-Type @"
public class Shift {
     public static int   Right(int x,   int count) { return x >> count; }
     public static uint  Right(uint x,  int count) { return x >> count; }
     public static long  Right(long x,  int count) { return x >> count; }
     public static ulong Right(ulong x, int count) { return x >> count; }
     public static int    Left(int x,   int count) { return x << count; }
     public static uint   Left(uint x,  int count) { return x << count; }
     public static long   Left(long x,  int count) { return x << count; }
     public static ulong  Left(ulong x, int count) { return x << count; }
  }                    
"@

function CombinationWithoutRepetition ([int]$k, $List)
{
  Function IsNBits ([long]$value, $k, $length)
  {
    $count = 0
    for ($i = 0 ; $i -le $length ; $i++)
    {
      if ($value -band 1)
      {
        $count++
      }
      $value = [shift]::Right($value,1)
    }

    if ($count -eq $k)
    {
      return $true
    }
    else
    {
      return $false
    }
  }

  Function BitsToArray ([long]$value, $List)
  {
    $res = @()
    for ($i = 0 ; $i -le $List.length ; $i++)
    {
      if ($value -band 1)
      {
        $res += $List[$i]
      }
      $value = [shift]::Right($value,1)
    }  

    return ,$res
  }

  [long]$i = [Math]::Pow(2, $List.Length)
  $res = @()
  for ([long]$value=0 ; $value -le $i ; $value++)
  {
    if ((IsNBits $value $k $List.Length) -eq $true)
    {
      #write-host $value
      $res += ,(BitsToArray $value $List)
    }
  }
  return ,$res
}

Clear-Host
$res = CombinationWithoutRepetition $k $List
$res.count
$res | %{$_ |% {}{Write-Host -NoNewline $_}{Write-Host ""}}