How to modify data in a Text File in VB .NET - vb.net

i have text file more than 2000 row like these:
10
21
13
...
and i want to find the avarge of the 1440 row ,start from down to up and find the max,then find the avarge for each 30 row and put them besid the data and find the max of these avarge like this
max(od data)=----
max(averge)=-----

While the question shows a lack of effort, I'll still give some basic guidelines to help your search.
Here are some things you are going to have to understand to tackle your problem:
1. How to handle text files in .NET
You can easily process files using the System.IO.File class. This class has several static methods that are very useful. (Static methods allow you to call the method without explicitly creating an object
System.IO.File Reference on MSDN
System.IO.File.ReadAllLines This method lets you read each line into an array
ReadAllLines is most useful when the file is short enough to read all at once. At 2000 rows this should not be a problem. If you had millions of rows you would have to look at how to work with something called streams (deal with data in small chunks)
2. How to convert a String to a number
The strings you read in with ReadAllLines aren't very useful as strings. You need to convert them to numbers to do math with them. And of course there is a class for that...
System.Int32.Parse Converts a string to a number, throws an exception for bad formats
System.Int32.TryParse Converts a string to a number, returns a default value on error
3. How to do a for loop in VB.NET
Any introductory tutorial should cover for loops, but here is one from MSDN
For Loops in VB.NET
4. How to do something every nth time through a loop
Use the modulus operator. This operator is like division, except that it returns the remainder. Every time the mod operation returns zero you have an exact multiple.
Example of using the Mod operator in VB.NET
5. How to find the max in a list of numbers
Have a variable to store the max value. Give it a value that is less than any value. Int32.MinValue is a safe value. Loop through every number. If it is larger than the max value, assign it to max value (it's the new max value). When you have processed every number max value contains the largest number you were able to find.
There are a few other details but if you can accomplish 1-5 you'll be able to ask a more specific question. This type of specific question will be better received by the stackoverflow community.
Happy coding.

Related

Elm: Search Number in Bytes

I'm trying to find some exif data in an image.
So first I need to find the number 0x45786966 ('Exif' as unsignedInt32) and store the offset.
The next two bytes should be zeros and after that the endianness as unsignedInt16 (either 0x4d4d or 0x4949) which should be stored too.
I can get the image as Bytes with the elm/file module.
But how do I search the 'Exif' start and parse the endianness in those Bytes?
I looked at the loop-example from elm/bytes but do not fully understand it.
First it reads the length of a list (unsignedInt32) and then it reads byte by byte?
How would this work if I want to read unsignedInt32s instead of bytes?
How do I set an offset to indicate where functions like unsignedInt32 should read next?
The example is talking about structured data with a known size field at the start. In your case, what you want to do is a search, so it is a rather different problem.
The problem is elm/bytes isn't really designed to handle searching. If you can guarantee the part you are looking for will be byte aligned, it may well be possible to do this, but given just what you have said, there isn't an easy way, as you can't iterate bit-by-bit.
You would have to read in values without alignment and then manually search for the part of the number you want within that. Given the difficulty and inefficiency of that approach, I would recommend using ports instead for that use case.
If you can guarantee that what you are searching for will be byte-aligned (or better yet, aligned to the length of your number), you can decode a byte at a time until you find what you are looking for. There is no way to read from a given offset, if you want to read to a certain point, you'd need to read and throw away values.
To do this, you would want to set up a loop where your state contains how much of the value you are looking for you have found. Each step, you check if you have the whole thing (success), you have the next part (continue), or you have something different (reset the state to search from the start again). If you reach the end without finding it, you have failed.

How might one most efficiently calculate contingent values?

Suppose that I have 10 values n_1, n_2, ... n_10 and that given any 1 of these value, the other 9 can be calculated. Let f_i(n_j) be the function that calculates the value n_i using the values of n_j (where i != j). These functions are relatively simple (i.e. contain no more than a few exponential functions or powers).
In terms of the functions used, what would be the most efficient way of creating a program to calculate the other 9 values in n_1, ..., n_10 given the 1 that is initially known?
Would the best option be to minimize the number of functions used (and thus minimize the number of lines of code), or to create a function defining every single mapping?
For example, would it be most efficient to use only the 18 functions
f_1(n_2), f_1(n_3), ..., f_1(n_10) [1]
f_2(n_1), f_3(n_1), ..., f_10(n_1) [2]
And then, for whatever input is provided by the user, the value of n_1 may be calculated by using the relevant function in line 1, from which every other value of intererest may be calculated using functions from line [2]?
Or would it be better to define all 90 mappings, and so that only a single function (rather than 2 functions) must be called to calculate each of the 9 other values?
Edit: The specific result that I am trying to achieve is as follows...
I am currently using VBA, with a user form of the following format:
The conversion frequency is a required field (so lets just say, for example, that it is always equal to 2 and forget about it). I want to use on change events so that whenever the user changes any of the 6 fields below the conversion frequency field, the other 5 fields are auto-filled with the correct value. However, since the user need only update any one out of six fields, with the other 5 fields being calculated from this, we will require 6^6-6 = 30 different functions to do these calculations. We will thus end up with a lot of repetitive code.
My question regards the best practices to follow when working with a form where one of many inputs may be provided, and all other fields must be updated as a result of the input provided and its value.
Or, equivalently, is there a way to update all fields when the value of one field changes? Can this be done without the number of lines of code required increasing exponentially as the number of fields increases?
I think you are grossly overthinking this. Think of this in terms of the formulas you need; which I think are 6. 6 functions that take 5 inputs each:
calculateEIR(nominalInterestRate, ForceOfInterest, DiscountFactor, EffectiveDiscountRate, NominalDiscountRate)
calculateNIR(EffectiveInterestRate, ForceOfInterest, DiscountFactor, EffectiveDiscountRate, NominalDiscountRate)
' and so on...
The event handlers, and the code to calculate the values are their own thing. Your onchange event handlers simply need to call the correct methods; this is 6 event handlers calling 5 methods each, so 11 functions if you want to keep count. It's a lot of copypasta. For example:
sub textEffectiveInterestRate_onchange()
Me.textNominalInterstRate.value = calculateNIR(Me.textEffectiveInterestRate.value, Me.textForceOfInterest.value, etc...)
Me.textForceOfInterest.value = calculateForceOfInterest(Me.textEffectiveInterestRate.value, Me.textNominalInterstRate.value, etc...)
' And every other function aside from calculateEIR()
end sub
I am unsure about the specifics of how you are changing all the values based on a change in the others (since I don't know the formulas), but in general, you should not in any way need 30 functions...

What is the time complexity of Search in ArrayList?

One interview question which I couldn't answer and couldn't find any relevant answers online.
I know the arraylist retrieve the data in constant time based on the indexes.
Suppose in an arraylist, there are 10000 data and the element is at 5000th location(We are not given the location), we have to search for a particular value( for eg integer 3 which happens to be on the 5000th index), for searching the value, we will have to traverse through the arraylist to find the value and it would take linear time right??
Because if we are traversing through the arraylist to find the data, it would take linear time and not constant time.
In short I want to know the internal working of contains method in which I have to check for the particular value and I don't have the index. It will have to traverse through the array to check for the particular value and it would take O(n) time right?
Thanks in advance.
I hope this is what you want to know about search in ArrayList:
Arrays are laid sequentially in memory. This means, if it is an array of integers that uses 4 bytes each, and starts at memory address 1000, next element will be at 1004, and next at 1008, and so forth. Thus, if I want the element at position 20 in my array, the code in get() will have to compute:
1000 + 20 * 4 = 1080
to have the exact memory address of the element. Well, RAM memory got their name of Random Access Memory because they are built in such way that they have a hierarchy of hardware multiplexers that allow them to access any stored memory unit (byte?) in constant time, given the address.
Thus, two simple arithmetic operations and one access to RAM is said to be O(1). See link to original answer.

Which data type to use for ordinal?

Whenever I have some records/objects that I want to be in a certain order, I usually create a field called Ordinal.
I often wonder if it would be better to use an integer or a decimal value for the ordinal field.
This is a consideration when moving an object to a different position in the order:
If you use consecutive integers, you have to do some serious reworking of all of the ordinals (or at least the ordinals that fall before the original position of the object being moved).
If you use integers but space them out (maybe at 1000 intervals), then you can just change the ordinal to a mid point value between the surrounding objects where you want to move the object. This could fail if somewhere down the line you end up with consecutive integers.
If you use decimal numbers you could just find the average of the surround object's ordinals and use that for the object to be moved.
Maybe it would be possible to use a string, but I could see that getting pretty goofy.
I'm sure there are other considerations I haven't thought of.
What do you use and why?
"This could fail if somewhere down the line you end up with consecutive integers."
For this (probably rare and thus not performance important) case, you could implement a renumber method that spaces out again. When I used to program in COMAL (anyone know that language?), you could do this very thing with line numbers.
Decimals seem to solve your problem pretty well. Since Decimals are just base 10 floats, you actually have a lot of digits available. Unless you've seen cases where you've gotten out to quite a few digits and had reason to suspect a reason for an unlimited number of digits being necessary, I'd let it ride.
If you really need an alternative and don't see a need to stick with a basic data bype, you might go with tumbler arithmetic. The basic idea is that it's a place notation that is infinitely expandable at each position. Pretty simple conceptually.
I used to use a decimal type for a field of this kind to order records in a table, which we actually exposed to the customer so that they could set their own order. Although it sounds cheesy our customers liked it; they found it very intuitive. They caught on very quickly that they could use numbers like 21.5 to move something between 21 and 22.
Maybe it's because they were accountants.
I use integers and just rearrange as necessary when a new item needs to be inserted in the middle of the order. Since you can create the necessary gap with a single update statement, it's fairly trivial. However, I've only ever done this on lookup tables of a few dozen rows at most, obviously this scales a bit poorly. But I would say that if you need a solution to this problem for a large number of rows, the process(es) for maintaining the order should be proceduralized anyway, which makes the choice of data type largely moot.
I remember this being a similar question to a previous post. It can be found here:
SQL Server Priority Ordering
The linked list would still work, but this is a much easier solution if you don't want to track a parent child relationship.
Sounds like what you want is a linked list. That way you always know what comes next and you don't have to guess. So the position field would be a pointer to the object following it.
The problem I have always had with using arbitrary numbers for position, is that it can quickly fall to entropy. What if more items get added and the number become consecutive etc. etc. It can quickly become unmanageable if the list of items changes position.
To implement this in sql server table, add another field with the same data type as the primary key. If the field is null then it is the bottom element in the list. If you are storing multiple lists in the same table you will probably want to add another field called ListID which designates all rows with the same ListID pertain to the same list. So something like this.
Table:
ID INT
ListID INT
Child INT
Pararent Row For first list:
1, 1, 2
First Child
2, 1, 3
Second Child
3, 1, NULL
Parent Row for second list:
4, 2, 5
First Child
5, 2, 6
Second Child
6, 2, NULL
You'll probably have to do an insert and an update every time you add a row, which can be a little tedious, but it will always make the list line up.
Is the "certain order" based on data outside of the table? If so, why not include it so you can do the sorting dynamically? If it's already in the table, adding a field is redundant.

Knapsack algorithm for time

I am using VB.NET and I am trying to come up with some algorithm or some pseudo-code, or some VB.NET code that will let me do the following (hopefully I can explain this well):
I have 2 collection objects, Cob1 and Cob2. These collection objects store objects that implement an interface called ICob. ICob has 3 properties. A boolean IsSelected property, a property called Length, which returns a TimeSpan, and a Rating property, which is a short integer.
OK, now Cob1 has about 100 objects stored in the collection and Cob2 is an empty collection. What I want to do is select objects from Cob1 and copy them over to Cob2. I want the following rules obeyed when selecting the objects though:
I want to be able to specify a timespan and I want enough objects to be selected to fit into the timespan I specify (based on the Length property). So for example, if I pass a 10 minute timespan to my function, it should pick enough objects that fill the entire 10 minute window, or come as close to filling it as possible.
No objects should be selected twice.
Objects that have a higher rating (via the Rating property) should have a better chance at being picked then other objects.
No object that has been selected in the last 30 minutes should be selected again (so that each object will eventually get selected at least once), regardless of rating.
Can anyone give me some tips on how to achieve this? The tips can be in the form of mental processes, VB.NET example code, Pseudo-code or just about anything else that might help me.
Thanks
EDIT:
Maybe It would help to everyone if I revealed what I'm trying to do in real life.
I am writing software for a radio station that will automatically select the music and advertisments to play, kinda of like a computerized program manager.
The length represents the length of the sound byte (either a song or an advertisement) and the rating is just that. If the song is popular, it gets more airtime. If an advertiser pays more money, then it also gets more airtime.
So my program should pick songs that play for 20 minutes or so, then pick some advertisements to play for about 5 minutes or so.
Hopefully this helps a little.
Thanks for the input from everyone!
Alan
Note that:
The restriction 1 is from the classical knapsack problem, which works on sets, as requested by restriction 2.
Restriction 3 is rather vague. It is better to have higher value or higher coverage of the lifespan? If you don't specify a objective function to maximaze (or, to be precise, there are two: lifespan itself and rate), there are some pareto optimal solutions.
Restriction 4 is implementable by making a map object -> last time selected., in the form of black list.
Long story short: first I'd filter the set by blacklisting the object by restriction 4, and then apply a knapsack algorithm.
In order to implement 4., I believe you'll need to save the date/time when the Cob was last selected. Then, I'd do it in the following steps:
Filter out the ones that have not been selected within the last 30 minutes.
Sort by rating and set your "cursor" on the first item in the list.
Check the item's timespan. If short enough to fit in the specified time, select it. If not, goto 3 and proceed with the next item.
Check if your timespan has been filled. If yes, you are done. If no, goto 3 and proceed with the next item.