How to choose an random object depending on its attribute - algorithm

I have an array filled with objects, each object has an attribute named amount. I want to subtract a given number evenly from random objects based on the amount.
I'll better explain it on the following example:
Dim subtractBy as integer = 5 'means i want to substract a total of 5
Dim Generator As System.Random = New System.Random()
While (subtractBy > 0)
Dim randomItem = array2(Generator.Next(0, array2.Count))
If (randomItem.amount > 0 ) Then
randomItem.changeAmountBy(-1)
subtractBy = subtractBy - 1
End If
End While
The problem with that example is, every object has the same chance to be choosen for substraction. I want that every object gets higher chances linear to the amount atribute. So an object with amount=6 has 6x higher chance to be selected than the object with amount=1 and so on.
(Althought the example is in VB, I appreciate also general non-code answers)
Thank you

Related

How do I add noise/variability to a dataset in Python, given the CV?

Given a dataset of blood results, say cholesterol level, and knowing that the instrument that produced those results is subject to a known degree of variability, how would I add that variability back into the dataset? i.e. I want to assume the result in the original dataset is the true/mean value, and then produce new results that are subject to the known variability of the instrument.
In Excel you use =NORM.INV(RAND(), mean, std_dev), where RAND() provides a random value between 0 and 1, "mean" will be the original value and I have the CV so I can calculate the SD. NORM.INV then provides the inverse of the cumulative normal distribution function.
I've done the following to create a new column with my new values, but would like to know if it is valid (i.e., will each row have a different random number between 0 and 1 as the probability? and is this formula equivalent to NORM.INV?
df8000['HDL_1'] = norm.ppf(random(), loc = df8000['HDL_0'], scale = TAE_df.loc[0,'HDL'])
Thanks in advance!

Input to different attributes values from a random.sample list

so this is what I'm trying to do, and I'm not sure how cause I'm new to python. I've searched for a few options and I'm not sure why this doesn't work.
So I have 6 different nodes, in maya, called aiSwitch. I need to generate random different numbers from 0 to 6 and input that value in the aiSiwtch*.index.
In short the result should be
aiSwitch1.index = (random number from 0 to 5)
aiSwitch2.index = (another random number from 0 to 5 different than the one before)
And so on unil aiSwitch6.index
I tried the following:
import maya.cmds as mc
import random
allswtich = mc.ls('aiSwitch*')
for i in allswitch:
print i
S = range(0,6)
print S
shuffle = random.sample(S, len(S))
print shuffle
for w in shuffle:
print w
mc.setAttr(i + '.index', w)
This is the result I get from the prints:
aiSwitch1 <-- from print i
[0,1,2,3,4,5] <--- from print S
[2,3,5,4,0,1] <--- from print Shuffle (random.sample results)
2
3
5
4
0
1 <--- from print w, every separated item in the random.sample list.
Now, this happens for every aiSwitch, cause it's in a loop of course. And the random numbers are always a different list cause it happens every time the loop runs.
So where is the problem then?
aiSwitch1.index = 1
And all the other aiSwitch*.index always take only the last item in the list but the time I get to do the setAttr. It seems to be that w is retaining the last value of the for loop. I don't quite understand how to
Get a random value from 0 to 5
Input that value in aiSwitch1.index
Get another random value from 0 to 6 different to the one before
Input that value in aiSwitch2.index
Repeat until aiSwitch5.index.
I did get it to work with the following form:
allSwitch = mc.ls('aiSwitch')
for i in allSwitch:
mc.setAttr(i + '.index', random.uniform(0,5))
This gave a random number from 0 to 5 to all aiSwitch*.index, but some of them repeat. I think this works cause the value is being generated every time the loop runs, hence setting the attribute with a random number. But the numbers repeat and I was trying to avoid that. I also tried a shuffle but failed to get any values from it.
My main mistake seems to be that I'm generating a list and sampling it, but I'm failing to assign every different item from that list to different aiSwitch*.index nodes. And I'm running out of ideas for this.
Any clues would be greatly appreciated.
Thanks.
Jonathan.
Here is a somewhat Pythonic way: shuffle the list of indices, then iterate over it using zip (which is useful for iterating over structures in parallel, which is what you need to do here):
import random
index = list(range(6))
random.shuffle(index)
allSwitch = mc.ls('aiSwitch*')
for i,j in zip(allSwitch,index):
mc.setAttr(i + '.index', j)

Generating Random Numbers and Letters

Keep getting this error sometimes when mid is ZERO:
Invalid procedure call or argument: 'Mid'
How would I fix this?
Function CreateRandomString(iSize)
Const VALID_TEXT = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
Dim sNewSearchTag
Dim I
For I = 0 To iSize
Randomize
sNewSearchTag = sNewSearchTag & Mid(VALID_TEXT,Round(Rnd * Len(VALID_TEXT)),1)
Next
CreateRandomString = sNewSearchTag
End Function
For the random range to be correct you need to make sure the random value generated is between 1 and the length of the VALID_TEXT string value.
The simple formula to do this using Rnd() is
(Rnd() * Len(VALID_TEXT)) + 1
also move Randomize() outside the loop, as it is you'll just make it less random as you're resetting the seed with every iteration of the loop.
The reason for the error is Mid() expects a valid start and size, which a zero value is not. See this question for more information.
More information about random number ranges can be found in this answer to another question.
The second argument of Mid is 1 based. That means that if you did:
Mid(VALID_TEXT,1,1)
you will get "a", not "b" as you might be expecting.
An easy fix would be to add 1 to the second argument, but then you'll run into the same problem on the top end. Typically people will round a random number down after multiplying it instead of using Math.Round, either view Math.Floor or Integer truncation.

VB: Calcute mean/average for udt array

I have an array of a struct
Private Type udtSingle
Dim Count As Long
Dim Value As Single
end Type
Private m(2) As udtSingle
Let's say the array is filled like this:
m(0).Count = 5
m(0).Value = 100
m(1).Value = 1
m(1).Count = 10
You can see that we have 5*100 and 1*10.
What would be the best way to calcuate the average?
for i as integer = 0 to m.upperbound()
cAll += m(i).Count * m(i).Value
iCount+=m(i).Count
next i
dim average as currency
average = cAll / iCount
That would work, but I have really many .Count and high .Value, and I am afraid of an overflow.
What else could I do, please?
If the array gets really huge, I will get an overflow anyway. Can I not calculate the average anew within the for-next-statement? I guess so, but I can think of an elegant solution.
ps: Yes, I know, the code is kind of pseudo-code...
Declare cAll as Double to avoid an overflow.
Dim cAll as Double
and then
cAll += Convert.ToDouble(m(i).Count) * Convert.ToDouble(m(i).Value)
Double range is up to approximately ±1.7 × 10^308.

Suggest an algorithm/method for finding a proper value

I have a bunch of values, for example: [1,2,14,51,100,103,107,110,300,505,1034].
And I have a pattern values, for example [1,10,20,100,500,1000].
I need to get the best 'suitable' value FROM pattern. In my example it is 100. How can I detect this value?
Example from life. The app has a bunch of distances between user position and some objects. The app also has a preset filter by distance: [1 meter, 10 meters, 20 meters, 100 meters]. I heed to set the filter by default not just to the first value (1 meter in my example), but to the value which match the bunch of distances the best way(100 meter in my example). I need to detect one value.
Thank you for help and any ideas.
I would say create a function like this (this is not real code) :
var ratio1 = 0.66
var ratio2 = 1.5
function Score(currentPatternValue, arrayOfValues)
{
count = 0
for each value in arrayOfValues <br>
if value > ratio1 * currentPatternValue AND value < ratio2 * currentPatternValue<br>
count++<br>
return count
}
then you run this for each value in your pattern values and pick the one with the highest score returned from that function

Resources