Question

Combinations of 12 numbers that add to 100

I'm looking for a piece of code that generates every possible combination of 12 POSITIVE numbers between 0 and 100 that add to 100.

Any questions please let me know.

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-08-31 at 12:19:21ID24695843
Topic

Microsoft Visual Basic.Net

Participating Experts
3
Points
500
Comments
27

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Every possible combination code.
    I need a piece of code that can give me every possible combination for a situation. Here is the situation A user has on his screen a text box for every hour of the day (24 text boxes). s/he enters into each box the total number of entities they requre on site in each hour...
  2. all possible combination of a number
    Hi I am just learning C by myself. I tried to write a program that does the follwing: I want to print all possible combination of numbers between 1-n. For example if the user input 2 cells and number between 0-1 the computer must print all possible combination of 0 and 1: 0 ...
  3. Combining Fields
    I'm in a hurry so big points for this... Using Access 2000 I have a database with a few tables in it. I have a particular query which I run to then export as a text file and upload to a website for online searching. My question is with respect to combining a bunch of field...
  4. Combination
    Cells A1 to A30 have values in them. Cell B1 is a target value. Can anyone send me instructions and the code I need to select the combination of A1:A30 that gets closest to the value in B1. Results must be B2 is the sum of the values in the combination. B3 and C3 is the diffe...
  5. Algorithm (Combination)
    Anyone know any good algorithm to print all "N" combinations from 13? What I meant of combination is like this : numbers = 0,1,2,3,4,5,6,7,8,9,10,11,12 5 combination from numbers : 0,1,2,3,4 0,1,2,3,5 0,1,2,3,6 0,1,2,3,7 ... ... etc. The sequence is not import...
  6. Number combinations
    How can I get every five digit number combination from a group on numbers using every number from 1-38 and not have any duplicate five digit numbers?

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: sl8rzPosted on 2009-08-31 at 12:46:54ID: 25225771

Try this:

 Private Function test100() As String
        Dim results As String = ""
        For i As Int32 = 0 To 100
            For j As Int32 = 0 To 100
                If i + j = 100 Then
                    results += i.ToString & ", " & j.ToString & ": "
                End If
            Next
        Next
        Return results
    End Function

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:

Select allOpen in new window

 

by: NULL_ReferenceExceptionPosted on 2009-08-31 at 13:28:25ID: 25226175

I think that will give me every combination of 2 numbers that add up to 12.

I'm going for something like this:

Period1      100
Period2      0
Period3      0
Period4      0
Period5      0
Period6      0
Period7      0
Period8      0
Period9      0
Period10      0
Period11      0
Period12      0

Period1      99
Period2      1
Period3      0
Period4      0
Period5      0
Period6      0
Period7      0
Period8      0
Period9      0
Period10      0
Period11      0
Period12      0

Period1      98
Period2      1
Period3      1
Period4      0
Period5      0
Period6      0
Period7      0
Period8      0
Period9      0
Period10      0
Period11      0
Period12      0


All 3 "sets" have 12 numbers that all sum to 100.  I'm looking to generate every possible "set".

 

by: sl8rzPosted on 2009-08-31 at 13:42:32ID: 25226316

Sorry for the oversight.  This really sounds like homework to me.  If it isn't then forgive me.  That being said, you really only need to add one more loop and keep everything else the same...you're almost there.

 

by: Idle_MindPosted on 2009-08-31 at 14:10:25ID: 25226589

Is the "order" important?

In other words, are these equivalent?

Period1      100
Period2      0
Period3      0
Period4      0
Period5      0
Period6      0
Period7      0
Period8      0
Period9      0
Period10      0
Period11      0
Period12      0

Period1      0
Period2      100
Period3      0
Period4      0
Period5      0
Period6      0
Period7      0
Period8      0
Period9      0
Period10      0
Period11      0
Period12      0

Period1      0
Period2      0
Period3      100
Period4      0
Period5      0
Period6      0
Period7      0
Period8      0
Period9      0
Period10      0
Period11      0
Period12      0

...and you would only want unique combinations of 12 numbers that add up to 100?

 

by: ChaosianPosted on 2009-08-31 at 14:20:41ID: 25226659

Do the 12 numbers have to be unique?

There's also some optimization you can do... for example, if 0 is not an option, then no loop has to count higher than 89. In addition, loop 12 only has to check to 89 - (loop1 + loop2 + ... + loop11).

You've also got the issue of sorting out duplicates, which will make this rather interesting. You may want to do something like start loop2 at the current value of loop1, loop3 at the current value of loop2, etc.

Otherwise... well, you're looking at 100^12 or 10^24 operations. Somehow, I suspect you're going to find out that your prof gave the problem for exactly this reason.

 

by: ChaosianPosted on 2009-08-31 at 14:48:56ID: 25226850

Well, the problem was actually interesting enough that I solved it. This is code-behind on a simple form with one button.

I've left some diagnostic code in place, so I'd be interested in knowing if anyone can come up with something more efficient.

Note that this code MAY NOT BE USED for academic purposes without proper attribution.

Public Class Form1
	' This code is copyright Jeff Certain, 2009
	' It may be used freely in production, but *must* be properly attributed for any academic use
	Private _currentLevel As Integer = 1
	Private _numberOfLevels As Integer = 12
	Private _targetValue As Integer = 100
 
	Private Sub FindSums(ByVal numberOfIntegers As Integer, ByVal targetValue As Integer)
		_numberOfLevels = numberOfIntegers
		_targetValue = targetValue
 
		For i As Integer = 0 To _targetValue
			Dim values As New IntegerList(_numberOfLevels)
			CheckAllRemainingOptions(i, values)
		Next
	End Sub
 
	Private Sub CheckAllRemainingOptions(ByVal input As Integer, ByVal values As IntegerList)
		Try
			_currentLevel += 1
			If _currentLevel = _numberOfLevels - 1 Then
				values(_currentLevel) = _targetValue - values.Sum
 
				Dim outputString As New System.Text.StringBuilder(32)
				For Each value As Integer In values
					outputString.AppendFormat("{0}, ", value.ToString)
				Next
				Console.WriteLine(outputString.ToString.Substring(0, outputString.Length - 2))
			Else
				For i As Integer = input To _targetValue - input
					values(_currentLevel) = i
					CheckAllRemainingOptions(i, values.Copy)
				Next
			End If
			_currentLevel -= 1
		Catch ex As Exception
			Throw ex
		End Try
	End Sub
 
	Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
		Dim sw As New Stopwatch
		sw.Start()
		FindSums(12, 100)
		sw.Stop()
		Console.WriteLine("Time: {0} ms", sw.ElapsedMilliseconds)
	End Sub
End Class
 
Public Class IntegerList
	Inherits List(Of Integer)
 
	Private Sub New()
		MyBase.New()
	End Sub
 
	Public Sub New(ByVal capacity As Integer)
		MyBase.New()
 
		If capacity < 1 Then Exit Sub
 
		For i As Integer = 1 To capacity
			Me.Add(0)
		Next
	End Sub
 
	Public Function Sum() As Integer
		For Each value As Integer In Me
			Sum += value
		Next
	End Function
 
	Public Function Copy() As IntegerList
		Dim output As New IntegerList()
		output.AddRange(Me.ToArray)
		Return output
	End Function
End Class
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:

Select allOpen in new window

 

by: sl8rzPosted on 2009-08-31 at 14:53:11ID: 25226879

Wow....

 

by: ChaosianPosted on 2009-08-31 at 14:54:17ID: 25226883

Made the mistake of running that, did you? LOL

And that was the optimized version!

 

by: NULL_ReferenceExceptionPosted on 2009-08-31 at 15:27:48ID: 25227099

No, this is not for academic purposes...

I'm working on building a forecasting model for a wholesale distribution company.  We stock about 45k unique SKUs.  We would like to, at any time, be able to calculate a rolling 12 month forecast.

The plan is to use the historical sales to assign a growth factor to each SKU.  We'll then use that growth factor to calculate the next 12 months sales.  We're going to use the prior 12 months sales to come up with the growth, but the question is how much weight do I put on each month?  Obviously more weight should be given to recent months, but too much weight on the most recent period will (possibly) put an increased weight on a month that could be higher or lower based on normal business volatility.

I'd like to come up with all the possible combinations of weight for each of the past 12 months.  They sum to 100 here, but really they'll sum to 1.  Then, using each "scenario" of 12 month growth factors, I'm going to go back and calculate the actual growth factors for each month, what the "scenario" would have estimated for the growth factor, and the forecast error.  After doing that for every scenario * 45k sku locations, I plan to see which growth factor scenario produces the lowest forecast error.  That'll become the monthly weighting scenario for the next quarter.  Every quarter or so I'll probably review it.

Make sense?

 

by: ChaosianPosted on 2009-08-31 at 15:30:21ID: 25227113

Well, in that case, the code I posted will give you all the combinations. There's going to be a metric buttload of them, though!

To get decimal values will require a little tweaking of the code, unless you want to just divide by 100.

 

by: ChaosianPosted on 2009-08-31 at 15:40:36ID: 25227174

Found a bug. Updated code follows.

Note that this code doesn't exclude all possible duplicate combinations. For what you want to do, that's probably a good thing.

Public Class Form1
	' This code is copyright Jeff Certain, 2009
	' It may be used freely in production, but *must* be properly attributed for any academic use
	Private _currentLevel As Integer = 1
	Private _numberOfLevels As Integer = 12
	Private _targetValue As Integer = 100
 
	Private Sub FindSums(ByVal numberOfIntegers As Integer, ByVal targetValue As Integer)
		_numberOfLevels = numberOfIntegers
		_targetValue = targetValue
 
		For i As Integer = 0 To _targetValue
			Dim values As New IntegerList(_numberOfLevels)
			CheckAllRemainingOptions(i, values)
		Next
	End Sub
 
	Private Sub CheckAllRemainingOptions(ByVal input As Integer, ByVal values As IntegerList)
		Try
			_currentLevel += 1
			If _currentLevel = _numberOfLevels - 1 Then
				If values.Sum > _targetValue Then Exit Sub
 
				values(_currentLevel) = _targetValue - values.Sum
 
				Dim outputString As New System.Text.StringBuilder(32)
				For Each value As Integer In values
					outputString.AppendFormat("{0}, ", value.ToString)
				Next
				Console.WriteLine(outputString.ToString.Substring(0, outputString.Length - 2))
			Else
				For i As Integer = input To _targetValue - input
					values(_currentLevel) = i
					CheckAllRemainingOptions(i, values.Copy)
				Next
			End If
			_currentLevel -= 1
		Catch ex As Exception
			Throw ex
		End Try
	End Sub
 
	Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
		Dim sw As New Stopwatch
		sw.Start()
		FindSums(12, 100)
		sw.Stop()
		Console.WriteLine("Time: {0} ms", sw.ElapsedMilliseconds)
	End Sub
End Class
 
Public Class IntegerList
	Inherits List(Of Integer)
 
	Private Sub New()
		MyBase.New()
	End Sub
 
	Public Sub New(ByVal capacity As Integer)
		MyBase.New()
 
		If capacity < 1 Then Exit Sub
 
		For i As Integer = 1 To capacity
			Me.Add(0)
		Next
	End Sub
 
	Public Function Sum() As Integer
		For Each value As Integer In Me
			Sum += value
		Next
	End Function
 
	Public Function Copy() As IntegerList
		Dim output As New IntegerList()
		output.AddRange(Me.ToArray)
		Return output
	End Function
End Class

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:

Select allOpen in new window

 

by: ChaosianPosted on 2009-08-31 at 15:42:29ID: 25227185

As a matter of interest, are you using .NET 3.5?

If so, you *could* download the parallel extensions to the framework (which will ship out-of-the-box with 4.0) and we could make the about code run on multiple cores...

 

by: ChaosianPosted on 2009-08-31 at 15:46:58ID: 25227211

Ok. Found another bug. Modify line 46 to test with FindSum(3, 100) to see what the issue was.

Public Class Form1
	Private _currentLevel As Integer = 0
	Private _numberOfLevels As Integer
	Private _targetValue As Integer
	Private _totalResults As Integer = 0
 
	Private Sub FindSums(ByVal numberOfIntegers As Integer, ByVal targetValue As Integer)
		_numberOfLevels = numberOfIntegers
		_targetValue = targetValue
 
		For i As Integer = 0 To _targetValue
			Dim values As New IntegerList(_numberOfLevels)
			CheckAllRemainingOptions(i, values)
		Next
	End Sub
 
	Private Sub CheckAllRemainingOptions(ByVal input As Integer, ByVal values As IntegerList)
		Try
			_currentLevel += 1
			If _currentLevel = _numberOfLevels Then
				If values.Sum > _targetValue Then Exit Sub
 
				values(_currentLevel - 1) = _targetValue - values.Sum
 
				Dim outputString As New System.Text.StringBuilder(32)
				For Each value As Integer In values
					outputString.AppendFormat("{0}, ", value.ToString)
				Next
				Console.WriteLine(outputString.ToString.Substring(0, outputString.Length - 2))
				_totalResults += 1
			Else
				For i As Integer = input To _targetValue - input
					values(_currentLevel - 1) = i
					CheckAllRemainingOptions(i, values.Copy)
				Next
			End If
			_currentLevel -= 1
		Catch ex As Exception
			Throw ex
		End Try
	End Sub
 
	Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
		Dim sw As New Stopwatch
		sw.Start()
		FindSums(12, 100)
		sw.Stop()
		Console.WriteLine("Time: {0} ms", sw.ElapsedMilliseconds)
	End Sub
End Class
 
Public Class IntegerList
	Inherits List(Of Integer)
 
	Private Sub New()
		MyBase.New()
	End Sub
 
	Public Sub New(ByVal capacity As Integer)
		MyBase.New()
 
		If capacity < 1 Then Exit Sub
 
		For i As Integer = 1 To capacity
			Me.Add(0)
		Next
	End Sub
 
	Public Function Sum() As Integer
		For Each value As Integer In Me
			Sum += value
		Next
	End Function
 
	Public Function Copy() As IntegerList
		Dim output As New IntegerList()
		output.AddRange(Me.ToArray)
		Return output
	End Function
End Class

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:

Select allOpen in new window

 

by: NULL_ReferenceExceptionPosted on 2009-08-31 at 17:40:53ID: 25227698

I modified this a bit so it runs as a console application and writes out to a text file.  Question, it seems like its working well for 3 values, but nothing beyond that.  How can I expand this so it does the combinations for all 12 periods?

Module Module1
    Private _currentLevel As Integer = 0
    Private _numberOfLevels As Integer
    Private _targetValue As Integer
    Private _totalResults As Integer = 0
    Public MyWriter As System.IO.TextWriter
 
    Sub main()
        Dim sw As New Stopwatch
        MyWriter = System.IO.File.AppendText("C:\GrowthFactorsText.txt")
        sw.Start()
        FindSums(12, 100)
        sw.Stop()
        Console.WriteLine("Time: {0} ms", sw.ElapsedMilliseconds)
    End Sub
 
 
    Private Sub FindSums(ByVal numberOfIntegers As Integer, ByVal targetValue As Integer)
        _numberOfLevels = numberOfIntegers
        _targetValue = targetValue
 
        For i As Integer = 0 To _targetValue
            Dim values As New IntegerList(_numberOfLevels)
            CheckAllRemainingOptions(i, values)
        Next
    End Sub
 
    Private Sub CheckAllRemainingOptions(ByVal input As Integer, ByVal values As IntegerList)
        Try
            _currentLevel += 1
            If _currentLevel = _numberOfLevels Then
                If values.Sum > _targetValue Then Exit Sub
 
                values(_currentLevel - 1) = _targetValue - values.Sum
 
                Dim outputString As New System.Text.StringBuilder(32)
                For Each value As Integer In values
                    outputString.AppendFormat("{0}, ", value.ToString)
                Next
                Console.WriteLine(outputString.ToString.Substring(0, outputString.Length - 2))
 
                MyWriter.WriteLine(outputString.ToString.Substring(0, outputString.Length - 2))
                MyWriter.Flush()
                _totalResults += 1
            Else
                For i As Integer = input To _targetValue - input
                    values(_currentLevel - 1) = i
                    CheckAllRemainingOptions(i, values.Copy)
                Next
            End If
            _currentLevel -= 1
        Catch ex As Exception
            Throw ex
        End Try
    End Sub
    Public Class IntegerList
        Inherits List(Of Integer)
 
        Private Sub New()
            MyBase.New()
        End Sub
 
        Public Sub New(ByVal capacity As Integer)
            MyBase.New()
 
            If capacity < 1 Then Exit Sub
 
            For i As Integer = 1 To capacity
                Me.Add(0)
            Next
        End Sub
 
        Public Function Sum() As Integer
            For Each value As Integer In Me
                Sum += value
            Next
        End Function
 
        Public Function Copy() As IntegerList
            Dim output As New IntegerList()
            output.AddRange(Me.ToArray)
            Return output
        End Function
    End Class
 
End Module
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:

Select allOpen in new window

 

by: NULL_ReferenceExceptionPosted on 2009-08-31 at 17:49:11ID: 25227726

Nope, I'm using .net 2.0.  

 

by: NULL_ReferenceExceptionPosted on 2009-08-31 at 18:40:02ID: 25227960

I kina understand what you did, but it's a little advanced for me.  I'm working with the attached code at this point.  I ran it for 80million combinations, but it was probably only a small % of the way through.  I'm counting by 5's now and we'll see where that takes me.

Thanks all for your help.

Module Module1
 
    Sub Main()
        Dim i1 As Integer = 0
        Dim i2 As Integer = 0
        Dim i3 As Integer = 0
        Dim i4 As Integer = 0
        Dim i5 As Integer = 0
        Dim i6 As Integer = 0
        Dim i7 As Integer = 0
        Dim i8 As Integer = 0
        Dim i9 As Integer = 0
        Dim i10 As Integer = 0
        Dim i11 As Integer = 0
        Dim i12 As Integer = 0
 
        Dim Output As String = ""
        Dim Counter As Integer = 0
        Dim Counter2 As Integer = 0
        Dim StepLevel As Integer = 5
 
        Dim MyWriter = System.IO.File.AppendText("C:\GrowthFactorsText.txt")
 
        For i1 = 0 To 100 Step StepLevel
            For i2 = 0 To 100 Step StepLevel
                For i3 = 0 To 100 Step StepLevel
                    For i4 = 0 To 100 Step StepLevel
                        For i5 = 0 To 100 Step StepLevel
                            For i6 = 0 To 100 Step StepLevel
                                For i7 = 0 To 100 Step StepLevel
                                    For i8 = 0 To 100 Step StepLevel
                                        For i9 = 0 To 100 Step StepLevel
                                            For i10 = 0 To 100 Step StepLevel
                                                For i11 = 0 To 100 Step StepLevel
                                                    For i12 = 0 To 100 Step StepLevel
                                                        If i1 + i2 + i3 + i4 + i5 + i6 + i7 + i8 + i9 + i10 + i11 + i12 = 100 Then
                                                            'Output = i1.ToString & "|" & i2.ToString & "|" & i3.ToString & "|" & i4.ToString _
                                                            '& "|" & i5.ToString & "|" & i6.ToString & "|" & _
                                                            '    i7.ToString & "|" & i8.ToString & "|" & i9.ToString & "|" & i10.ToString & "|" & i11.ToString & "|" & i12.ToString
                                                            'System.Console.WriteLine(Output)
                                                            'MyWriter.WriteLine(Output)
                                                            'MyWriter.Flush()
 
                                                            Counter = Counter + 1
                                                            Counter2 = Counter2 + 1
                                                            If Counter2 = 100000 Then
                                                                System.Console.WriteLine(Counter)
                                                                MyWriter.WriteLine(Counter)
                                                                MyWriter.Flush()
                                                                Counter2 = 0
                                                            End If
                                                        End If
 
                                                    Next
                                                Next
                                            Next
                                        Next
                                    Next
                                Next
                            Next
                        Next
                    Next
                Next
            Next
        Next
        MyWriter.WriteLine(Counter)
    End Sub
 
End Module

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:

Select allOpen in new window

 

by: NULL_ReferenceExceptionPosted on 2009-08-31 at 18:42:01ID: 25227972

Idle_Mind, to answer your earlier question, yes, the order is important, since each # represents a growth factor being applied to a month of sales.

 

by: Idle_MindPosted on 2009-08-31 at 19:02:00ID: 25228061

I haven't studied Jeffs code at all so apologies if this uses a similar mechanism...  =)

The below is a modification of my revision class here:
http://www.experts-exchange.com/Programming/Languages/.NET/Visual_Basic.NET/Q_23723548.html#22452485

It allows you to specify a unique sequence of characters (integers in your case) and then "counts" using that sequence producing a "revision sequence".  The code in the link showed how to make all revisions of a specific length (length 2 from 3 letters 'ABC').

Here is the code modified for your situation:
(It's been running about 10 minutes on my system and the output file is currently at 45 MB....don't open that in NotePad my friend!)

Module Module1
 
    Sub Main()
        Dim UniqueValues As New List(Of Integer)
        For i As Integer = 0 To 100
            UniqueValues.Add(i)
        Next
        Dim StartCombo As New List(Of Integer)
        For i As Integer = 1 To 12
            StartCombo.Add(0)
        Next
        Dim combos As New Combinations(UniqueValues, StartCombo)
 
        Dim MyDocs As String = My.Computer.FileSystem.SpecialDirectories.MyDocuments
        Dim FileName As String = "GrowthFactorsText.txt"
        Dim OutputFile As String = System.IO.Path.Combine(MyDocs, FileName)
        Dim Writer As New System.IO.StreamWriter(OutputFile)
 
        Console.WriteLine("Started at: " & DateTime.Now)
        Console.WriteLine("Processing...please be VERY patient!...")
 
        Dim SW As New Stopwatch
        SW.Start()
 
        Dim Total As Integer
        Dim Output As String
        Dim Combo As List(Of Integer)
        Dim StringValues As List(Of String)
        combo = combos.Combination
        While combo.Count = StartCombo.Count
            Total = 0
            For Each value As Integer In combo
                Total = Total + value
            Next
            If Total = 100 Then
                StringValues = Combo.ConvertAll(AddressOf IntToString)
                Output = String.Join(",", StringValues.ToArray)
                Writer.WriteLine(Output)
            End If
            combo = combos.NextCombination
        End While
 
        Writer.Close()
        SW.Stop()
 
        Console.WriteLine("Stopped at: " & DateTime.Now)
        Console.WriteLine("Total Processing Time: " & SW.Elapsed.Hours & " hours, " & SW.Elapsed.Minutes & " minutes, " & SW.Elapsed.Seconds & " seconds")
    End Sub
 
    Private Function IntToString(ByVal int As Integer) As String
        Return int.ToString
    End Function
 
    Public Class Combinations
 
        Private _UniqueValues As New List(Of Integer)
        Private _Combination As New List(Of Integer)
 
        Public Sub New(ByVal UniqueValues As List(Of Integer), ByVal StartingCombination As List(Of Integer))
            _UniqueValues = UniqueValues
            _Combination = StartingCombination
        End Sub
 
        Public ReadOnly Property Combination() As List(Of Integer)
            Get
                Dim output As New List(Of Integer)
                output.AddRange(_Combination.ToArray)
                Return output
            End Get
        End Property
 
        Public Function NextCombination(Optional ByVal NumJumps As Integer = 1) As List(Of Integer)
            Dim forward As Boolean = (NumJumps > 0)
            NumJumps = Math.Abs(NumJumps)
            Dim i As Integer
            For i = 1 To NumJumps
                If forward Then
                    Me.Increment()
                Else
                    Me.Decrement()
                End If
            Next
            Return Me.Combination
        End Function
 
        Private Sub Increment()
            Dim CurValue As Integer = _Combination(_Combination.Count - 1)
            Dim index As Integer = _UniqueValues.IndexOf(CurValue)
            If index < (_UniqueValues.Count - 1) Then
                index = index + 1
                _Combination(_Combination.Count - 1) = _UniqueValues(index)
            Else
                _Combination(_Combination.Count - 1) = _UniqueValues(0)
                Dim i As Integer
                Dim startPosition As Integer = _Combination.Count - 2
                For i = startPosition To 0 Step -1
                    CurValue = _Combination(i)
                    index = _UniqueValues.IndexOf(CurValue)
                    If index < (_UniqueValues.Count - 1) Then
                        index = index + 1
                        _Combination(i) = _UniqueValues(index)
                        Exit Sub
                    Else
                        _Combination(i) = _UniqueValues(0)
                    End If
                Next
                _Combination.Insert(0, _UniqueValues(0))
            End If
        End Sub
 
        Private Sub Decrement()
            Dim CurValue As Integer = _Combination(_Combination.Count - 1)
            Dim index As Integer = _Combination.IndexOf(CurValue)
            If index > 0 Then
                index = index - 1
                _Combination(_Combination.Count - 1) = _UniqueValues(index)
            Else
                _Combination(_Combination.Count - 1) = _UniqueValues(_UniqueValues.Count - 1)
                Dim i As Integer
                Dim startPosition As Integer = _Combination.Count - 2
                For i = startPosition To 0 Step -1
                    CurValue = _Combination(i)
                    index = _UniqueValues.IndexOf(CurValue)
                    If index > 0 Then
                        index = index - 1
                        _Combination(i) = _UniqueValues(index)
                        Exit Sub
                    Else
                        _Combination(i) = _UniqueValues(_UniqueValues.Count - 1)
                    End If
                Next
                _Combination.RemoveAt(0)
                If _Combination.Count = 0 Then
                    _Combination.Insert(0, _UniqueValues(0))
                End If
            End If
        End Sub
 
    End Class
 
End Module
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:

Select allOpen in new window

 

by: ChaosianPosted on 2009-08-31 at 22:15:42ID: 25228682

I'm not entirely sure why the loop is abnormally terminating. I expect it has something to do with my recursion counter. I'll have to look at it more in the morning.

 

by: Idle_MindPosted on 2009-08-31 at 23:22:00ID: 25228932

Just thought I'd mention that with my system you can stop the process and then later start it back up at the same point by passing in the last used sequence as the "StartCombo".  In the original code, we are starting with all 0 (zeros):

        Dim UniqueValues As New List(Of Integer)
        For i As Integer = 0 To 100
            UniqueValues.Add(i)
        Next
        Dim StartCombo As New List(Of Integer)
        For i As Integer = 1 To 12
            StartCombo.Add(0)
        Next
        Dim combos As New Combinations(UniqueValues, StartCombo)

You could just as easily start with any other combination though!  The system "counts" much like we do...

If you passed in( 2, 4, 6) as the UniqueValues and (2, 2) as the StartCombo you would get:

2, 2
2, 4
2, 6
4, 2
4, 4
4, 6
6, 2
6, 4
6, 6

The approach is not based on nested loops or recursion so theoretically it can "count" any number of values for any given length.  I really don't know how it compares speedwise though...it is definitely a NON-OPTIMIZED brute force algorithm.

Without the external check on the Size of the combos (the While loop check) it will continue counting and increasing the size of the sequence.  After (6, 6) above, you would get:

2, 2, 2
2, 2, 4
2, 2, 6
2, 4, 2
2, 4, 4
etc...

I just noticed a bug in my submission as well, though...change the Combinations Class constructor to:

        Public Sub New(ByVal UniqueValues As List(Of Integer), ByVal StartingCombination As List(Of Integer))
            _UniqueValues = UniqueValues
            _Combination.AddRange(StartingCombination.ToArray)
        End Sub

 

by: ChaosianPosted on 2009-09-01 at 05:40:44ID: 25230913

I'm going to have to let Mike take the points for this one. I can't see why my algorithm isn't working.

I do, however, think that recursion is a far more flexible way to go. I'll play more with this and post a working solution later today.

 

by: ChaosianPosted on 2009-09-01 at 07:18:50ID: 25231812

Ok... *now* it works....

Module Module1
	Sub Main()
		Dim finder As New CombinationFinder(100, 12)
		finder.Start()
		Console.ReadLine()
	End Sub
End Module
 
Public Class CombinationFinder
	Private _targetNumber As Integer
	Private _numberOfNumbers As Integer
 
	Public Sub New(ByVal targetNumber As Integer, ByVal numberOfNumbers As Integer)
		_targetNumber = targetNumber
		_numberOfNumbers = numberOfNumbers
	End Sub
 
	Public Sub Start()
		Dim values As New SummedList
		FindSums(values)
	End Sub
 
	Public Sub FindSums(ByVal values As SummedList)
		If values.Count < _numberOfNumbers Then
			For i As Integer = 0 To Math.Max(_targetNumber - values.Sum, 0)
				Dim newValues As SummedList = values.Copy
				newValues.Add(i)
				FindSums(newValues)
			Next
		Else
			If values.Sum = _targetNumber Then
				Dim outputString As New System.Text.StringBuilder(32)
				For Each item As Integer In values
					outputString.AppendFormat("{0}, ", item)
				Next
 
				Console.WriteLine(outputString.ToString.Substring(0, outputString.ToString.Length - 2))
			End If
		End If
	End Sub
End Class
 
Public Class SummedList
	Inherits List(Of Integer)
 
	Public Function Sum() As Integer
		For Each item As Integer In Me
			Sum += item
		Next
	End Function
 
	Public Function Copy() As SummedList
		Copy = New SummedList
		Copy.AddRange(Me.ToArray)
	End Function
End Class

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:

Select allOpen in new window

 

by: Idle_MindPosted on 2009-09-01 at 08:20:22ID: 25232487

Very nice Jeff...compact and elegant.  =)

My code is basically an iterative version of your recursion and thus generates the sequences in the same order...but mine is non-optimized so it produces a lot of un-necessary combos that exceed the target sum.  Again, mine is definitely the brute force "dumb" one.  It's a nice approach, though, for when you need to get the next combo in the sequence iteratively and can't have the recursive loops getting in the way (like in response to an Event for example).

On your code, I think we code ~squeeze~ just a LITTLE more speed out of it like this:

    Public Sub FindSums(ByVal values As SummedList)
        If values.Sum = _targetNumber Then
            While values.Count < _numberOfNumbers
                values.Add(0)
            End While

            Dim outputString As New System.Text.StringBuilder(32)
            For Each item As Integer In values
                outputString.AppendFormat("{0}, ", item)
            Next

            Console.WriteLine(outputString.ToString.Substring(0, outputString.ToString.Length - 2))
        ElseIf values.Count < _numberOfNumbers Then
            For i As Integer = 0 To Math.Max(_targetNumber - values.Sum, 0)
                Dim newValues As SummedList = values.Copy
                newValues.Add(i)
                FindSums(newValues)
            Next
        End If
    End Sub

This way, if your sum is already 100, you avoid making the expensive copies of the list (just to add zeroes) and also the overhead/performance hit of the recursive calls.

 

by: ChaosianPosted on 2009-09-01 at 08:46:06ID: 25232777

Nice addition. That's way more elegant than my brute-force recursion. Wish I'd done thunk of that :)

 

by: ChaosianPosted on 2009-09-28 at 07:05:23ID: 25439409

No objection here.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...