|
Thanks Pete, will read that right now!
DaveBTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)Visual Basic is not used by normal people so we're not covering it here. (Uncyclopedia)
|
|
|
|
|
Thanks for the link - I'd never looked at that pattern - I definately need to do some re-reading to 'freshen' up.
What I'm trying to do is more of a generic Observer type pattern, but using a Singleton for the subject so it's accessible by any instance of any type. Mika and I have got quite a way into this and it's pretty much working apart from this, which is a bit ugly at the moment. I've overloaded the Notify methods so that the instance can be sent as a parameter, but I'd rather make that part automated. The reference to the original instance must surely be somewhere(stack?) for the method to be able to return?
DaveBTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)Visual Basic is not used by normal people so we're not covering it here. (Uncyclopedia)
|
|
|
|
|
It is on the stack, but the problem is - .NET doesn't provide any way to get to this information.
|
|
|
|
|
Actually, thats not correct. .NET provides the StackFrame object, which does exactly that...lets you walk the stack and get callers up the chain. Try this:
using System.Diagnostics;
class Foo
{
public DoSomething()
{
Bar bar = new Bar();
bar.InternalCall(new object());
}
}
class Bar
{
[MethodImpl(MethodImplOptions.NoInlining)]
internal InternalCall(object param)
{
StackFrame frame = new StackFrame(1);
MethodBase callingMethod = frame.GetMethod();
Type callingType = callingMethod.DeclaringType;
}
}
|
|
|
|
|
Hello guys
i am new to C# and i have some problem that going to make my head explode
i am stuck on this thing for a week now
i need to read data file by column not by lines
for example
i have the following data file
6, 148, 72, 35, 0, 336, 0627, 50, 2
8, 183, 64, 0, 0, 233, 0672, 32, 2
1, 85, 66, 29
1, 89, 66, 23, 94, 281, 0167, 21, 1
0, 137, 40, 35, 168, 431, 2288, 33, 2, 10, 9, 125
5, 116, 74, 0, 0, 256, 0201, 30, 1
i need to read it coulmn by coulmn and store it to arrays
for exaample the first array would be {6,8,1,1,0,5} and so on
all what i have done is read it line by line and thats not working for me
can anyone help please
|
|
|
|
|
Hmm, this problem sounds familiar
If you got the file read line by line, you have to process all the data to get it into column arrays.
I will try to post pseudocode:
1. Read the file line by line storing the values in arrays (each line is an array) and save this line in a List.
2. After reading the whole file you know how many rows you got (size of the list). Build an array with this size (i will call this array the column-array)
3. Iterate through the list of rows, check if the list contains an entry for the current column and store the value to the array (column-array[iCurRow] = curList[iCurColumn]).
That's it.
Let me know if this helps you.
Regards
Sebastian
|
|
|
|
|
thanks for you help
this is what i've done so far
i read the data in array line by line
the problem that the line lenth is not equal as i illustrate in the example
i am still stuck
public class VariableTransformation
{
private String FileName = "";
private FileReader FileReader;
private BufferedReader buffFile;
private ArrayList<string[]> attrDomainList = new ArrayList<string[]>();
private String[] item=null;
public static void main(String[] args)
{
VariableTransformation tds = new VariableTransformation();
Scanner input=new Scanner(System.in);
System.out.println("===============================================");
System.out.print("Enter the file name>> ");
String filename;
filename=input.next();
tds.fileLoad(filename);
System.out.println("===============================================");
}
public void fileLoad(String fileName)
{
String line = "";
String[] attrDomain;
FileName = fileName;
System.out.println("> Reading File..");
try {
int lineCount=0;
int size=0;
FileReader = new FileReader(FileName);
buffFile = new BufferedReader(FileReader);
try {
while((line = buffFile.readLine()) != null)
{
item = line.split(",");
size=item.length;
attrDomain=new String[size];
for (int i = 0; i < item.length; i++) {
attrDomain[i]=item[i];
}
attrDomainList.add(attrDomain);
lineCount++;
}
printData(attrDomainList);
System.out.println("> Finish File Reading.");
System.out.println("Number of Lines>> "+lineCount);
System.out.println("===============================================");
}
catch (IOException e) {
System.out.println(e.getStackTrace().toString());
System.out.println("# Error while reading file .");
}
finally
{
try {buffFile.close();} catch (IOException e) {e.printStackTrace();}
try {FileReader.close();} catch (IOException e) {e.printStackTrace();}
}
} catch (FileNotFoundException e) {
System.out.println("> Error. Target File Don't exist.");
e.printStackTrace();
}
}
private void printData(ArrayList<string[]> dataFile )
{
int Counter=0;
for (int i = 0; i < dataFile.size(); i++) {
System.out.print("["+(++Counter)+"] ");
for (int j = 0; j < dataFile.get(i).length; j++) {
System.out.print(dataFile.get(i)[j]+" ");
}
}
}
}
|
|
|
|
|
Okay, so you have to check if the line exists or not. I will try to provide code (beware: not tested).
public void fileLoad(String fileName) {
int iMaxColumnCount = 0;
...
while((line = buffFile.readLine()) != null)
{
item = line.split(",");
size=item.length;
if(size > iMaxColumnCount)
iMaxColumnCount = size;
...
}
private List<string[]> TransformData(ArrayList<string[]> aData, int iMaxColumnCount) {
List<string[]> aTransformed = new List<string[]>();
for(int iCurColumn = 0; iCurColumn < iMaxColumnCount; iCurColumn++) {
string[] aValues = new string[aData.size()];
for(int iCurRow = 0; iCurRow < aData.size(); iCurRow++) {
if(aData[iCurRow].length > iCurColumn) {
aValues[iCurRow] = aData[iCurRow][iCurColumn];
}
}
aTransformed.Add(aValues);
}
return aTransformed;
}
That's it. The trick is to count the maximum column count during the file read. Then we can use this number to transform the input.
Pls let me know if this helps you.
Regards
Sebastian
|
|
|
|
|
yeah thats work
thaaaaaaaaaaaaaaaaaaaaaaaaank you so much you really helped me sooooooooooooooo much , i dont know how to thank you really
god bless you
|
|
|
|
|
Hi everyone!
I wanted to know how the ReaderWriterLock determines what is the "resource" in the code on which it has to accquire the reader lock or the writer lock, or how exactly does these locks work(internally). The MSDN article protects an static integer, but doesn't seem to specify how, as after acquiring a reader lock, writes can be done as in the following code:
ReaderWriterLock rw = new ReaderWriterLock();
int counter = 0;
try
{
rw.AcquireReaderLock(100);
try
{
Interlocked.Increment(ref counter);
}
finally
{
rw.ReleaseLock();
}
}
catch (ApplicationException)
{
Console.WriteLine("Failed");
}
Console.WriteLine(counter);
here we are acquiring an reader lock for 100ms, but writing to the data. Confused
|
|
|
|
|
Hi,
a ReaderWriterLock, just like all other synchronization tools, is just a tool; you must use it correctly in order to achieve your goals. It does not protect you, or any of your objects, against programming mistakes. For the RWL that means you must use it where ever you access the object you want protected against multi-threaded accesses, and you must be careful about calling the right method; it won't help much calling AcquireReaderLock() when you intend to write to the variable you are trying to protect.
|
|
|
|
|
Your blending two different kinds of locking. If you use Interlocked, all operations performed with it ARE thread-safe...you don't need to bother with a ReaderWriterLock. Interlocked is the lightest weight thread sync feature available in .NET, and it should be used in favor of any other locking when possible. I would recommend dropping the RWL and just keep the Interlocked.
|
|
|
|
|
In addition to the other replies...
Also keep in mind that the two methods of locking have different uses.
A ReaderWriterLock is for synchronizing access to a resource that
is read often but written to infrequently. That can give you better
performance than locking on every read and write.
Mark
Mark Salsbery
Microsoft MVP - Visual C++
|
|
|
|
|
Hi,
I'd like to run some simulations on a deck of 52 cards, but I don't know how to make it fast.
Say, I want to draw 5 random cards from a deck. The most straightforward way to do this would be to create a List<string>, List<card>, List<int>, etc. (whatever way the cards are represented), then draw a random number between 0-51, remove the card from the list, draw a number between 0-50, remove the card from the list, rinse & repeat until 5 cards are drawn.
The problem is that adding/removing stuff is a costly operation. Can you see a fast way to randomly draw cards from a deck?
|
|
|
|
|
I don't think it is such slow.
You may use an array (of card index or references) and that swap the random selected element with the last one.
If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler.
-- Alfonso the Wise, 13th Century King of Castile.
This is going on my arrogant assumptions. You may have a superb reason why I'm completely wrong.
-- Iain Clarke
[My articles]
|
|
|
|
|
That's a really nice idea. I'm going to try that.
|
|
|
|
|
Ok, I just quickly implemented what you describe, populating a List<int> with the numbers 0-51, and removing a random entry from the list 5 times.
I did this in a big loop that repeats the operation a million times, and it took roughly a second.
So unless you're planning on implementing your own List, rather than using the Generics one, I wouldn't worry about speed
|
|
|
|
|
Well 1 million is what I need in fact ;o
Thank you for trying. It took 1 second even when you have to repopulate the list at every pass? I need to see this by myself!
|
|
|
|
|
This took 2.7s on my machine. What's your code?
List<uint> deck = new List<uint>();
uint[] cards = new uint[52];
Random rnd = new Random();
DateTime st = DateTime.Now;
for (int i = 0; i < 1000000; i++)
{
deck.Clear();
deck.AddRange(cards);
deck.RemoveAt(rnd.Next(0, deck.Count - 1));
deck.RemoveAt(rnd.Next(0, deck.Count - 1));
deck.RemoveAt(rnd.Next(0, deck.Count - 1));
deck.RemoveAt(rnd.Next(0, deck.Count - 1));
deck.RemoveAt(rnd.Next(0, deck.Count - 1));
}
DateTime ed = DateTime.Now;</uint></uint>
|
|
|
|
|
Random rnd = new Random();
List<int> myDeck = new List<int>();
DateTime start = DateTime.Now;
for (int loop = 0; loop < 1000000; ++loop)
{
myDeck.Clear();
for (int i = 0; i < 52; ++i)
{
myDeck.Add(i);
}
List<int> hand = new List<int>();
// Randomly remove a random card until the deck is empty
for( int draw = 0; draw<5; ++draw )
{
int cardIndex = rnd.Next(myDeck.Count);
int card = myDeck[cardIndex];
myDeck.RemoveAt(cardIndex);
hand.Add(card);
}
}
DateTime end = DateTime.Now;
[edit] - turned off the html tags - which kills the formatting, but at least you can see the generics!
Help me! I'm turning into a grapefruit!
Buzzwords!
|
|
|
|
|
Don't move the data around so much... Instead of shifting half the deck to remove a card, just move the last card into the empty slot.
Runs in 125 ms. on my puter:
public class Deck {
private int[] _cards;
private int _used;
private Random _rnd;
public Deck() {
_cards = new int[52];
_used = 0;
_rnd = new Random();
}
public void Init() {
for (int i = 0; i < 52; i++) {
_cards[i] = i;
}
_used = 52;
}
public void GetHand(int[] hand) {
for (int i=0;i<5;i++) {
int index = _rnd.Next(_used);
hand[i] = _cards[index];
_used--;
_cards[index] = _cards[_used];
}
}
}
Deck deck = new Deck();
int[] hand = new int[5];
for (int i = 0; i < 1000000; i++) {
deck.Init();
deck.GetHand(hand);
}
Despite everything, the person most likely to be fooling you next is yourself.
|
|
|
|
|
Hi,
the strategy of putting all candidates in a collection, and extracting from there as many as you need in a random way, is correct. However, if you only want to extract a small fraction, it may be more economical to forget the collection, and just try 5 random numbers; whenever one is chosen that has been picked already, just throw the dice again. For 5 out of 52 that will occur in some 10% of the cases.
If on the other hand, you decide to stick with the collection, there is no real need to build it over and over; once done, you can add the chosen items back to the collection. That would change the order, but then you could sort the collection (not sure that would be faster than recreating it), or you could ignore the issue, just relying on the randomness of the picking process. Strict randomness would mean the outcome does not depend on the previous outcome, so all candidates have the same probability, no matter where they are in the collection.
Of course, if you are creating the perfect poker playing app, and are gambling your fortune, you may want to make sure, and follow the official ways...
Luc Pattyn [Forum Guidelines] [My Articles]
I use ListBoxes for line-oriented text (not TextBoxes), and PictureBoxes for pictures (not drawings).
modified on Friday, June 10, 2011 12:23 PM
|
|
|
|
|
Luc Pattyn wrote: If on the other hand, you decide to stick with the collection, there is no real need to build it over and over; once done, you can add the chosen items back to the collection.
Interresting idea. It shaved off about 25% of the executon time of the code I posted earlier. What I did was actually to leave the chosen items in the array, only swapping them to the unused area at the end.
Despite everything, the person most likely to be fooling you next is yourself.
|
|
|
|
|
Yes I did that too, and it ran pretty fast. (400ms on my old comp)
It's probably the best method. The List approach is really too slow for what I need (Monte Carlo simulations).
Thanks everyone for your time.
|
|
|
|
|
Hi Guffa,
I didn't see your code until now; if you have an array, rather than a vague collection, swapping cards out of sight as you did is the right way to go IMO. Reinserting the chosen ones would mean: undo the swaps (which you should do in reverse order of course). The advantage now is you are restoring
the exact state the array had to begin with without touching things that hadn't changed in the process.
Luc Pattyn [Forum Guidelines] [My Articles]
I use ListBoxes for line-oriented text (not TextBoxes), and PictureBoxes for pictures (not drawings).
modified on Friday, June 10, 2011 12:23 PM
|
|
|
|
|