从数组中找到数字的所有组合以达到给定的总和

时间:2019-06-25 13:57:36

标签: vb.net sum

我正在学习 vb.net ,所以我对此进行了很多搜索,但找不到解决方案。

我有一个数组:

{1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768,65536}

可以看出,它是以下2^n序列。

如何以优化的方式获得总和与给定值匹配的所有数组?

示例:

  1. 总和:64->结果:{64}
  2. 总和:80->结果:{16,64}或{64,16}(仅这些数组之一)
  3. 总和:162->结果:{128,32,2}

3 个答案:

答案 0 :(得分:1)

另一种选择是使用Convert.ToString()(将二进制数指定为2)将您的数字转换为二进制表示形式。然后简单地遍历字符串,对于遇到的每个“ 1”,根据当前位置计算等效的以2为底的幂。这种方法不需要2的幂的硬编码数组。

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim values() As Integer = {64, 80, 162}
    For Each value As Integer In values
        Dim powers As List(Of Integer) = GetBinaryPowers(value)
        Debug.Print(value & ": " & String.Join(", ", powers))
    Next
End Sub

Private Function GetBinaryPowers(ByVal number As Integer) As List(Of Integer)
    Dim powers As New List(Of Integer)
    Dim strBinary As String = Convert.ToString(number, 2)
    For i As Integer = 0 To strBinary.Length - 1
        If strBinary(i) = "1" Then
            powers.Add(Math.Pow(2, strBinary.Length - (i + 1)))
        End If
    Next
    Return powers
End Function

输出:

64: 64
80: 64, 16
162: 128, 32, 2

答案 1 :(得分:0)

您可以使用以下函数获取包含序列中所有数字的import numpy import cv2 import os from math import * def generate(f,a,b,min,max,functionname='noname'): ph=(b-a)/1920 pv=(max-min)/1080 picture=numpy.zeros((1080,1920)) for i in range(0,1920): picture[1079-(int((f(a+(i+1)*ph)*1080/max))),i]=255 for i in range(1920): picture[1079-(int((f(a+(i+1)*ph)*1080/max)))+1,i]=255 cv2.imwrite(functionname+'.png',picture) with open("function.py",'w') as file: f=input('enter the funtion you want to draw example: or e**x :\n') file.write("from math import *\ndef f(x):\n\treturn "+f) from function import f os.remove("function.py") d=input('enter the interval ,min ,max and the image file name. Separate characters with spacebar. Example: 0 1 0 14 exponontielle :\n').split(" ") generate(f,int(d[0]),int(d[1]),int(d[2]),int(d[3]),d[4]) 数组:

Integer

答案 2 :(得分:0)

Dim number As Int64 = 162
Dim factor As Integer = 0
Dim power As Int64
Dim numbers As New List(Of Int64)
Do
    power = 2 ^ factor
    If power > number Then
        Exit Do
    End If

    If (number And power) = power Then
        numbers.Add(power)
    End If

    factor += 1
Loop
相关问题