开发者

Print array length for each element of an array

Given a string array of variable length, print the lengths of each element in the array.

For example, gi开发者_高级运维ven:

string[] ex = {"abc", "adf", "df", "ergd", "adfdfd");

The output should be:

2 3 4 6

One possibility I'm considering is to use a linked list to save each string length, and sort while inserting and finally display the results.

Any other suggestions for efficient solutions to this problem?


Whenever you want to maintain a collection of distinct things (ie: filter out duplicates), you probably want a set.

There are many different data structures for storing sets. Some of these, like search trees, will also "sort" the values for you. You could try using one of the many forms of binary search trees.


What you are doing now (or the given answer) is called the insertion sort. It basically compare the length of the string-to-insert from the inserted strings. After then, when printing, teh length of string-to-print (at current pointer) will be compared to the length of the string before it and after it, if has the same length, do not print!

Another approach is, the bubble sort, it will sort two strings at a time, sort them, then move to next string...

The printing is the most important part in your program, regardless of what sorting algorithm you use, it doesn't matter.

Here's an algorithm for bubble sort and printing process, it's VB so just convert it...

    Dim YourString(4) As String
    YourString(0) = "12345" 'Will not be printed
    YourString(1) = "12345" 'Will not be printed
    YourString(2) = "123"   'Will be printed
    YourString(3) = "1234"  'Will be printed

    Dim RoundLimit As Integer = YourString.Length - 2

    'Outer loop for how many times we will sort the whole array...
    For CycleCounter = 0 To RoundLimit
        Dim CompareCounter As Integer

        'Inner loop to compare strings...
        For CompareCounter = 0 To RoundLimit - CycleCounter - 1

            'Compare lengths... If the first is greater, sort! Note: this is ascending
            If YourString(CompareCounter).Length > YourString(CompareCounter + 1).Length Then
                'Sorting process... 
                Dim TempString = YourString(CompareCounter)
                YourString(CompareCounter) = YourString(CompareCounter + 1)
                YourString(CompareCounter + 1) = TempString
            End If

        Next
    Next

    'Cycles = Array length - 2 , so we have 2 cycles here
    'First Cycle!!!
    '"12345","12345","123","1234" Compare 1: index 0 and 1 no changes
    '"12345","123","12345","1234" Compare 2: index 1 and 2 changed
    '"12345","123","1234","12345" Compare 3: index 2 and 3 changed
    'Second Cycle!!!
    '"123","12345","1234","12345" Compare 1: index 0 and 1 changed
    '"123","1234","12345","12345" Compare 2: index 1 and 2 changed
    '"123","1234","12345","12345" Compare 3: index 2 and 3 no changes
    'No more cycle!

    'Now print it! Or use messagebox...


    Dim CompareLimit As Integer = YourString.Length - 2

    For CycleCounter = 0 To CompareLimit
        'If length is equal to next string or the preceeding string, do not print...

        If ((CycleCounter - 1) <> -1) Then 'Check if index exist
            If YourString(CycleCounter).Length = YourString(CycleCounter - 1).Length Then
                Continue For 'The length is not unique, exit compare, go to next iteration...
            End If
        End If

        If ((CycleCounter + 1) <> YourString.Length - 1) Then 'Check if index exist
            If YourString(CycleCounter).Length = YourString(CycleCounter + 1).Length Then
                Continue For 'The length is not unique, exit compare, go to next iteration...
            End If
        End If

        'All test passed, the length is unique, show a dialog!
        MsgBox(YourString(CycleCounter))
    Next


The question as stated doesn't say anything about sorting or removing duplicates from the results. It is only the given output that implies the sorting and duplicate removal. It doesn't say anything about optimisation for speed or space or writing for maintainability.

So there really isn't enough information for a "best" solution.

If you want a solution that will work in most languages you probably should stick with an array. Put the lengths in a new array, sort it, then print in a loop that remembers that last value to skip duplicates. I wouldn't want to use a language that couldn't cope with that.

If a language is specified you might be able to take advantage of set or associate array type data structures to handle the duplicates and/or sorting automatically. E.g., in Java you could pick a collection class that automatically ignores duplicates and sorts, and you could structure your code such that a one line change to use a different class would let you keep duplicates, or not sort. If you are using C# you could probably write the whole thing as a one-line LINQ statement...


Here is a C++ solution:

#include <set>
#include <vector>
#include <string>
#include <iostream>

using namespace std;

int main()
{
  string strarr[] = {"abc", "adf", "df", "ergd", "adfsgf"};
  vector< string > vstr(strarr, strarr + 5);
  set< size_t > s;

  for (size_t i = 0; i < vstr.size(); i++)
  {
    s.insert( vstr[i].size() );
  }

  for (set<size_t>::iterator ii = s.begin(); ii != s.end(); ii++)
    cout << *ii << " ";
  cout << endl;

  return 0;
}

Output:

$ g++ -o set-str set-str.cpp 
$ ./set-str 
2 3 4 6 

A set is used because (quoting from here):

Sets are a kind of associative container that stores unique elements, and in which the elements themselves are the keys.

Associative containers are containers especially designed to be efficient accessing its elements by their key (unlike sequence containers, which are more efficient accessing elements by their relative or absolute position).

Internally, the elements in a set are always sorted from lower to higher following a specific strict weak ordering criterion set on container construction.

Sets are typically implemented as binary search trees.

And for details on vector see here and here for string.


Depending on the language, the easiest way might be to iterate through the array using a for loop

for (i=0;i<array.length;i++){
  print array[i].length;
}

do you need to print them in order?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜