CodeVerge.Net Beta


   Explore    Item Entry   Register  Login  
Microsoft News
Asp.Net Forums
IBM Software
Borland Forums
Adobe Forums
Novell Forums




Can Reply:  No Members Can Edit: No Online: Yes
Zone: > NEWSGROUP > Asp.Net Forum > windows_hosting.hosting_open_forum Tags:
Item Type: NewsGroup Date Entered: 7/6/2005 8:53:00 PM Date Modified: Subscribers: 0 Subscribe Alert
Rate It:
NR
XPoints: N/A Replies: 7 Views: 39 Favorited: 0 Favorite
8 Items, 1 Pages 1 |< << Go >> >|
mcmcomasp
Asp.Net User
creating a weighted array7/6/2005 8:53:00 PM

0

i am attempting to create a weighted array of values for my server control.

heres a bit of bkg

i have an XML doc that contains promo items we want to showcase. Currently i just grab all the dets from XML and insert them into a multi-dimensional array.  I want to multiply weighted items in my array so there's more chance of them being selected.  I figure the easiest way is to just make my array larger and have multiple instances of the heavier items in my array, that way when i pick a random index number theres more opportunity for the heavier ones to be selected.    Im assuming i'd have to make a parallel array of weights and use that to judge which values should be repeated.  I am a bit lost on how to do it so any information would be helpful.  Im hoping to just have weightings range from 1 to 5. 

im using the snippet below to add xml to my array;

if(catNode.Attributes["name"].InnerText.ToString().ToLower() == catname.ToString().ToLower())

{
//set max number of items & set new array size
int uBound = catNode.ChildNodes.Count;
promoList =
new string[uBound][];
//go through nodes
foreach(XmlNode promoNode in (XmlNodeList)catNode.ChildNodes)
{
   //set the second dimension of the array count of detail items
   promoList[i ] = new String[promoNode.ChildNodes.Count];
   int j=0;
   //iterate through details and add to array 2nd dimension
   foreach(XmlNode itemNode in (XmlNodeList)promoNode.ChildNodes)
   {
      promoList[i ][j] = itemNode.InnerText.ToString();
      j++;
   }
i++;

Heres an example of one of the XML items.

<promoItem>
<ItemID>2</ItemID>
<Title>Shopping Specials at XXXXXX</Title>
<ImageURL>./images/SHOPPING_promo.jpg</ImageURL>
<URL>http://www.XXXX.ca</URL>
<Copy>These Notebook Accessories are amazing</Copy>
<Weight>3</Weight>
</promoItem>

Thanks in advance.
mcm




techincal blog
corporate
codeboy
Asp.Net User
Re: creating a weighted array7/11/2005 9:09:24 PM

0

I would do it a little differently.  I'd load each of the xml items into a hashtable with a key that corresponds to the Item's ItemID.  I'd then create an array just as you mentioned but this would hold only the Item IDs X Weight, so you might have 3 ItemID 2s.  I'd randomly select a value from this array, and then pull the xml item out of the hashtable based on the selected ID value. 

Upon retrieving a value from the array i'd check to see that the hashtable[thatvalue] isn't null, if so then i'd pull out the xml value, use it and set it (in the hashtable) to null.  This way you don't have to worry about repeats.  Also you'd take less memory because you're only repeating the Item Ids instead of the whole xml. 

Hope this Helps
--Scott
Scott Sargent

Visit my Blog
mcmcomasp
Asp.Net User
Re: creating a weighted array7/13/2005 4:01:23 PM

0

thanks for the help.

i have created the hashtable but im still having logic problems with the array creation hopefully you can help me.

What im stumped on is creating the array with repeated items based on another array..

So for the code below i create the hashtable then create a array called promoWeights.  This array just has 8 numbers in it
5,3,1,1,2,1,3,4 <-  those are the weights.   So the first item in the hashtable needs to go in an array 5 times, then the next
item needs to go in three times, but i dont know how to re-index it properly.  i tried stuff like this but i cant figure it out.

Basiclly i need the algorythm to just take one array and duplicate values based on values in another array!
Can i use the array methods to do that, rather than looping.  (Ie can i do array.copy[index] or something??)

HTANKS

for(int i=0;i<mynewArray.length;++i)
{
   //repeat per weights 
k=0
  int topline = promoWeights[i ] + k
   for(int k=k;k<promoWeights[i ];++k){
      mynewArray[k] = promoWeights[i ];
  }

But that repeats over the first index.  i need to say OK NOW WERE AT ITEM 5 SO LETS SET THAT AS THE START POINT FOR K

foreach(XmlNode catNode in catNodes){

if(catNode.Attributes["name"].InnerText.ToString().ToLower() == catname.ToString().ToLower()){
promoWeights =
new string[catNode.ChildNodes.Count];
int j = 0;
//go through nodes
foreach(XmlNode promoNode in (XmlNodeList)catNode.ChildNodes)
{
//add to hasthable
htPromos.Add(promoNode.ChildNodes[0].InnerText.ToString(),promoNode.ChildNodes);
//add weight to array
promoWeights[j] = promoNode.ChildNodes[5].InnerText.ToString();
totalWeight += Convert.ToInt32(promoNode.ChildNodes[5].InnerText);
++j;
}


techincal blog
corporate
codeboy
Asp.Net User
Re: creating a weighted array7/13/2005 8:21:18 PM

0

well what about this: 

Let's say we have an item class ( this could be a wrapper for the xml elements you're using etc.. i'm just referencing it for simplicity).  Item will have 3 properties, ID, Weight and Value.  With value being the information that you'd display from the xml etc...

Hashtable itemContainer = new Hashtable();
Item myItem = null;
ArrayList weightedItemList = new ArrayList();
 int itemWgt = 0;

// load XML Element into Item class
// this would be in a for loop grabbing each xml element
myItem = LoadItem(MyXmlElement);
if(myItem != null)
{
   // add this to the hash table so we can retrieve its value
   itemContainer.Add(myItem.ID,myItem);   

   // add the items to the weighted list
   itemWgt = myItem.Weight;
  for(int i = 0; i < itemWgt; i++)
  {
      weightedItemList.Add(myItem.ID);
   }
}


// Now you've got a hashtable with one item for each Product item, and an Array list with SUM(Weight) elements in it. 
So to pull out the items we can do this:

int i = RandomNumberBetween0AndMaxOfArrayList(); // a randomly selected item from the arraylist;

Item myItem = itemContainer[weightedItemListIdea [I]];
if(myItem != null)
{
   // if we do not want duplicates set the item in the hashtable to null now
   itemContainer[weightedItemListIdea [I]] = null;
}
else
   // here you can loop back around to try to grab an item if you want.


This isn't a perfect or a finished solution, it will work best when you want to retrieve a subset of the total number of items, if you do not want duplicates it gets inefficient as the number of items you want to retrieve gets closer to the number of total items.  Its not a terrible start though and i think could form a workable solution.

Hope this helps.

Scott
Scott Sargent

Visit my Blog
mw:17:61
Asp.Net User
Re: creating a weighted array7/14/2005 11:36:29 PM

0

I whould use DataSet (DataTable) and sort it (using DataView) on weighting column.
+&up;
mcmcomasp
Asp.Net User
Re: creating a weighted array7/15/2005 1:54:46 AM

0

how would a heavier item be selected more than a lighter one? do you mean using the dataTable instead of the hashTable? 

If so could you explain a bit more?  

Whats faster a hashtable or dataset datatable.

thanks

mcm


techincal blog
corporate
mcmcomasp
Asp.Net User
Re: creating a weighted array7/15/2005 2:59:28 AM

0

thanks so much,  i used your idea of the ArrayList to save me the headache with looping and creating a normal array. Worked like a charm.  I'm posting the load event and the xmlLoad method so you can see how i integrated it into a random selection,  Please tell me what you think i would appreciate it greatly. 

The only methd i left out is what writs it to two stacked div cells,  all i do is cast a xmlNodeList from my hashTable item object and get the necessary childnodes from that and write them to a html string.
That gets fed into two stacked divs.  It works great and initial testing of the "randomness" of it is hopeful.  Out of 10 tests the code had to re-calc non-matching promotions only once.

thanks for all your help,
mcm

//page load event
  private void Page_Load(object sender, System.EventArgs e)
  {
   //create filepath and name
   string filepath = ConfigurationSettings.AppSettings["filepath"];
   string filename = ConfigurationSettings.AppSettings["filename"];
   string category = "";
   //determine if page.ID is on this page, if it is use it as category name.
   if(Page.ID == null)
   {
    category = (string)Request.Url.Segments[Request.Url.Segments.Length - 1];
   }
   else
   {
    category = Page.ID.ToString();
   }
   //get the promos
   ArrayList pickList = getPromos(filepath + filename,category);
   //create random number for first promo
   Random:
   Random rn = new Random();
   int idx = (int)rn.Next(pickList.Count);
   int promo1Id = Convert.ToInt32(pickList[idx]);
   int idx2 = (int)rn.Next(pickList.Count);
   int promo2Id = Convert.ToInt32(pickList[idx2]);
   if(promo1Id == promo2Id){goto Random;};
   //use random number to pick what to show.
   displayPromo(idx,promo1);
   displayPromo(idx2,promo2);
  }

  //gets the promos
  private ArrayList getPromos(string xmlFile,string catname)
  {
   try
   {
    XmlDocument xml = new XmlDocument();
    xml.Load(xmlFile);
    //get node list of categories
    XmlNodeList catNodes = xml.GetElementsByTagName("Category");
    //create hashtable & ArrayList
    Hashtable htPromos = new Hashtable();
    ArrayList pickList = new ArrayList();
    //loop through xml
    foreach(XmlNode catNode in catNodes)
    {
     if(catNode.Attributes["name"].InnerText.ToString().ToLower() == catname.ToString().ToLower())
     {
      //go through nodes
      foreach(XmlNode promoNode in (XmlNodeList)catNode.ChildNodes)
      {
       //add to hasthable
       htPromos.Add(promoNode.ChildNodes[0].InnerText.ToString(),promoNode.ChildNodes);
       //get weight
       int itemWeight = Convert.ToInt32(promoNode.ChildNodes[5].InnerText.ToString());
       //add item to picklist x times based on weight
       for(int i=0;i<itemWeight;++i)
       {
        pickList.Add(promoNode.ChildNodes[0].InnerText.ToString());

       } 
      }
     }
    }
    //insert the array and hashtable to cache
    Cache.Insert("picklist",pickList);
    Cache.Insert("htpromos",htPromos);
    //return array
    return pickList;
   }
   catch(XmlException xmlEx)
   {
    string errMsg = xmlEx.Message.ToString();
    return null;  
   }
  }


techincal blog
corporate
codeboy
Asp.Net User
Re: creating a weighted array7/15/2005 7:53:42 PM

0

That looks great, just be sure that you handle the case of a promo being null (ie you've already picked it).  Another enhancement you could think of making is to remove all of the Items from the weighted array list once you pick that item, that will reduce collisions / duplicates, but if you're just pulling a few items out of a larger list it really shouldn't be an issue at all. 

Looks Good!

--Scott
Scott Sargent

Visit my Blog
8 Items, 1 Pages 1 |< << Go >> >|


Free Download:

Books:
Introduction to Java Programming, Comprehensive Authors: Y. Daniel Liang, Pages: 1328, Published: 2008
Analogue IC design: the current-mode approach Authors: C. Toumazou, F. J. Lidgey, David Haigh, Institution of Electrical Engineers, Pages: 646, Published: 1990
Introduction to Adaptive Arrays Authors: Robert A. Monzingo, Thomas W. Miller, Pages: 543, Published: 2003
Handbook of exploration geophysics Authors: Paul A. Chapel, Pages: 411, Published: 1992

Web:
Random Weighted Elements in PHP Random Weighted Elements in PHP. I was writing some code for Adonomics when I ... Many other such functions work by creating an auxiliary array and filling ...
WARD: A Weighted Array Data Scheme for Subspace Processing in ... that the array output can be weighted by a single weighting .... in [15] that the weighted array data for the array noise with ...
Weighted random methods for Array [ruby] [random] [array] [weight] Nov 22, 2005 ... You need to create an account or log in to post comments to this site. ... Weighted Random array selection in ruby random array weighted ...
Weighted capacitor array with selective grouping to form array ... To view PDFs, Login or Create Account (Free!) Export Citation: .... A binary weighted array of capacitors comprising: a first set of unit capacitors having ...
Artifact Suppression in Imaging of Myocardial Infarction Using B1 ... B1-weighted phased-array combining provides an inherent degree of ghost artifact .... This may create an artifact due to the interleaved segmented ...


Videos:
Self Hypnosis - Powerfully Creating A New Path With Roger ... These videos are provided by http://www.hypnosishealthinfo.com/. Visit our blog at http://hypnosishealthinfo.com/blog/. Self Hypnosis ...
hjemvid Making the VikingHjem come to life was the whole point in it's creation and construction. It's definately come together to make an impression on ...
SSP (Space Solar Power) Analysis SSP (Space Solar Power) Analysis Original "whitepaper": http://www.scribd.com/doc/8736849/Space-Solar-Power-SSP-A-Solution-for-Energy ...
The Band EPK Jubilation This is one of my all time favorite films -- one of the greatest shoots I've had the honor to record. It was a short film to promote The Band's ...
Laparoscopic Incisional Ventral Hernia Repair from Univ of ... On Sept. 14, 2005, at 4 p.m., webcast viewers watched as Dr. Adrian Park, chief of general surgery at UMMC and professor of surgery at the ...






recommend a host for me, 10gb+, sql server ...

asp.net and domain host pointing

webcontrol problem, killing me

usercontrol & client

custom controls, viewstate and events

newbie:dependent dynamic drop down lists

is exists supporting sql express 2005 web hosting?

i need some help about webhosting requirements.

new httpresponse class, please help

i just converted to vs 2003... now none of my controls work in design mode.

design-time support for external stylesheets - possible?

gate.com

cannot add custom control to the webform !!?!!!

server controls -- getting the data

webhost4life problems

stringconverter on property always has context = null

building custom controls without visualstudio?

vs.net custom designer

making the custom scrollable datagrid

namespace in dll

how do you tell a good fast host?

find all the controls placed according to the tabindex set at design time of the page.

composite control, createchildcontrols question

designtime and dynamic propertys

postback data handler problem

dropdownlist .databinding disables itemplate instantiatein on postback

editabledatagrid won't work on web user control page

hosting accounts

raising event in custom control

alignment of control when cssclass is set

   
  Privacy | Contact Us
All Times Are GMT