简体   繁体   中英

I don't know how to move around words to reduce the number of lines of a txt file in C#

I'm trying to take an XML file that contains a random list of words that has a wrap limit and return the list of words in a txt file in an order which contains as few lines as possible in C#. It also contains a wrap feature so that if word that would be put on the line exceeds the wrap limit, the word is inserted into the next line

I understand the theory to do this: you apply the wrap and then create a new list, go down the list of words and find the first available space in the wrap. You then go down the list of words and if a word's length is less than the available space, designate the word as found. You then find the next space and start again. When there are no more lines, the words are inputted into a new list with the words designated as found going into the spaces that can fit them

For example: The wrap is 8 and the words are: abc tyur yuf oir a gt

The output after the wrap should be:

abc
tyur
yuf oir
a gt

And the final output should be like this

abc yuf
tyur yuf
oir a gt

I have managed to get the wrap working but I cannot figure out how to convert the theory of the line reduction into a method that works. Can anyone help?

Think of it as having a bunch of empty bins that are filled using the words provided.

A bin has a certain size.

Order the words by length descending.

Then go word by word and try to put it in one of the bins (incl. one space). If it fits, great, on to the next word.

If it doesn't fit, you create a new empty bin and put it into that one.

Take the next word and put it into a bin, starting with the first one that isn't full yet.

This might not be the perfect solution yet, but maybe the ideas come as you build that.

Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM