0

So here's an example of someone (me) writing very bad C# code.

I'm trying to figure out the best method of storing values and replacing them with values as they become known.

Here's how I had been doing it earlier:

int
EMA_Value_Prev4,
EMA_Value_Prev3,
EMA_Value_Prev2,
EMA_Value_Prev,
EMA_Value;

EMA_Value_Prev4 = EMA_Value_Prev3;
EMA_Value_Prev3 = EMA_Value_Prev2;
EMA_Value_Prev2 = EMA_Value_Prev;
EMA_Value_Prev = EMA_Value;
EMA_Value = 0;

//  In the below space, some code figures out what EMA_Value is

/*  Some amazing code */

//  EMA_Value now equals 245 (hypothetically).

Since then, I've used arrays to store this with for loops, like this:

 int [] EMA_Value = new int [5];

 for (xCount=4; xCount>1; xCount--)
    {EMA_Value[xCount] = EMA_Value[xCount - 1]; }   

For the way more advanced and experienced (and smarter) coder than I, what I should be doing instead that's either more efficient/elegant/process friendly?

Thanks in advance for any time or attention you give this question. :)

Spiderbird
  • 87
  • 2
  • 3
  • 8

1 Answers1

1

If the reason you're doing it that way is because you want to get the previous values in some case. You can think about using something like a Stack. .NET has a built in stack

Stack<int> stack = new Stack<int>();
stack.push(10)
int topValue = stack.pop()

Every time you get a new value, you call stack.push(newValue). If you want that the previous value, (behaving in the same way as the back button on a browser), you then use pop.

If you're using last N values for something like a runge-kutta ODE solver, than your solution with an array is as good as any other implementation

Eric Yang
  • 2,678
  • 1
  • 12
  • 18
  • Hi Eric, thank you very much for that! Implementation question though. Suppose I need to snag the value two layers deep in the Stack. Would that third line be "int 2ndValue = stack.pop(2); ? – Spiderbird Aug 06 '18 at 04:00
  • Pop will remove the value from the stack. So if you wanted the second value back, then you would just pop again. Pop doesn't take a parameter. If you want random access to the values instead of just the last one iteratively, then it's better to use your array implementation that you posted previously – Eric Yang Aug 06 '18 at 12:26
  • Great, thanks for the reply Eric. Hope your week goes well. – Spiderbird Aug 06 '18 at 14:55