Results 1 to 14 of 14

Thread: [RESOLVED] How to range an array?

  1. #1

    Thread Starter
    Fanatic Member Flashbond's Avatar
    Join Date
    Jan 2013
    Location
    Istanbul
    Posts
    646

    Resolved [RESOLVED] How to range an array?

    Hi Guys!

    First, I am using VS 2012.

    I have a number m and p(n) array.

    How to say;
    Code:
    rng= Lbound(p) to Ubound(p)
    
    For Each val in rng
    If Not m Mod val = 0 Then
    'Do something
    End If
    ???

    Basicly I want to be sure m is not divisible with none of the p() array values.

    Thanks a lot!

  2. #2
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Posts
    12,375

    Re: How to range an array?

    Hey flashbond, be sure to turn option strict/explicit on. As for your request, I would run a for loop to check if m is divisible with p(). Here is an example using a console application:
    Code:
    Option Strict On
    Option Explicit On
    Module Module1
    
        Sub Main()
            Dim p() As Integer = {4, 6, 8, 10, 12}
            Dim m As Integer = 4
    
            For i As Integer = 0 To p.Count - 1
                If CBool(p(i) Mod m) Then
                    Console.WriteLine(p(i).ToString & " is not divisible with " & m.ToString)
                End If
            Next
    
            Console.ReadLine()
        End Sub
    
    End Module
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | HtmlLessons | CssLessons | Code Tags | Sword of Fury - Jameram

  3. #3
    PowerPoster stanav's Avatar
    Join Date
    Jul 2006
    Location
    Providence, RI - USA
    Posts
    9,290

    Re: How to range an array?

    Try this:
    Code:
    Dim mIsOK As Boolean = True
    For Each value As Integer In PArray
       If M Mod value = 0 Then
          mIsOK = False
          Exit For
       End If
    Next
    If mIsOK then
       DoSomethingHere
    End If
    Let us have faith that right makes might, and in that faith, let us, to the end, dare to do our duty as we understand it.
    - Abraham Lincoln -

  4. #4

    Thread Starter
    Fanatic Member Flashbond's Avatar
    Join Date
    Jan 2013
    Location
    Istanbul
    Posts
    646

    Re: How to range an array?

    dday9: Yeah, I use a Do..Loop. It slows me down so much. Do you think For..Next will run faster?
    stanav: Looks so good. I'll try.

    Thanks for both replies!

  5. #5

    Thread Starter
    Fanatic Member Flashbond's Avatar
    Join Date
    Jan 2013
    Location
    Istanbul
    Posts
    646

    Re: How to range an array?

    dday9: Yeah, I use a Do..Loop. It slows me down so much. Do you think For..Next will run faster?
    stanav: Looks so good. I'll try.

    Thanks for both replies!

  6. #6
    Frenzied Member MattP's Avatar
    Join Date
    Dec 2008
    Location
    WY
    Posts
    1,227

    Re: How to range an array?

    Some other options would be Enmerable.Any to check if any of the values in the array are divisible by m or Enumerable.All to check whether all of the values aren't divisible by m.

    vb.net Code:
    1. Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    2.         Dim p1 = {2, 3, 5, 7, 11, 13, 17, 19}
    3.         Dim p2 = {1, 2, 3, 4, 5, 6, 7, 8}
    4.         Dim m = 4
    5.  
    6.         Dim isNotEvenlyDivisible1 = Not p1.Any(Function(p) p Mod m = 0)
    7.         Dim isNotEvenlyDivisible2 = Not p2.Any(Function(p) p Mod m = 0)
    8.  
    9.         Dim isNotEvenlyDivisible3 = p1.All(Function(p) p Mod m <> 0)
    10.         Dim isNotEvenlyDivisible4 = p2.All(Function(p) p Mod m <> 0)
    11.     End Sub
    This pattern in common to all great programmers I know: they're not experts in something as much as experts in becoming experts in something.

    The best programming advice I ever got was to spend my entire career becoming educable. And I suggest you do the same.

  7. #7
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,104

    Re: How to range an array?

    A Do loop is not inherently slower than a For Next, but it is fairly likely that in practice it will be very slightly slower. Frankly, the difference shouldn't matter unless the Do loop is doing something bad. In either case, LINQ, such as MattP showed, is tight, elegant, and slower. The difference between a For Next and LINQ is not enough that you will see it unless you are doing THOUSANDS of iterations, but it is there. When you use LINQ, you are basically making a trade between small, easy to write, code and performance. In almost all cases, the performance difference is effectively zero (I'm not going to get into it, but the two alternatives would end up taking the same amount of time if you measured them in a certain way). Therefore, if your Do loop is noticeably slower than the For Next, there is probably something wrong with the Do Loop.

    One other point is that arrays in .NET all start with 0. VB6 allowed array ranges, but that is no longer available. You could make an object that acted like an array with ranges, but it would be a whole lot of work for no material benefit.
    My usual boring signature: Nothing

  8. #8

    Thread Starter
    Fanatic Member Flashbond's Avatar
    Join Date
    Jan 2013
    Location
    Istanbul
    Posts
    646

    Re: How to range an array?

    Quote Originally Posted by MattP View Post
    Some other options would be Enmerable.Any to check if any of the values in the array are divisible by m or Enumerable.All to check whether all of the values aren't divisible by m.

    vb.net Code:
    1. Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    2.         Dim p1 = {2, 3, 5, 7, 11, 13, 17, 19}
    3.         Dim p2 = {1, 2, 3, 4, 5, 6, 7, 8}
    4.         Dim m = 4
    5.  
    6.         Dim isNotEvenlyDivisible1 = Not p1.Any(Function(p) p Mod m = 0)
    7.         Dim isNotEvenlyDivisible2 = Not p2.Any(Function(p) p Mod m = 0)
    8.  
    9.         Dim isNotEvenlyDivisible3 = p1.All(Function(p) p Mod m <> 0)
    10.         Dim isNotEvenlyDivisible4 = p2.All(Function(p) p Mod m <> 0)
    11.     End Sub
    Ok. This seems awsome but I didn't get it completely. Can you give an example of usage of function with only one array, please?

  9. #9
    PowerPoster dunfiddlin's Avatar
    Join Date
    Jun 2012
    Posts
    8,245

    Re: How to range an array?

    Quote Originally Posted by Flashbond View Post
    Ok. This seems awsome but I didn't get it completely. Can you give an example of usage of function with only one array, please?
    Er .... delete lines 3, 7 and 0 or 2, 6 and 9 and it is an example with only one array. There aren't any selections being made from both arrays (although that is perfectly feasible!)
    As the 6-dimensional mathematics professor said to the brain surgeon, "It ain't Rocket Science!"

    Reviews: "dunfiddlin likes his DataTables" - jmcilhinney

    Please be aware that whilst I will read private messages (one day!) I am unlikely to reply to anything that does not contain offers of cash, fame or marriage!

  10. #10
    PowerPoster Evil_Giraffe's Avatar
    Join Date
    Aug 2002
    Location
    Suffolk, UK
    Posts
    2,555

    Re: How to range an array?

    Quote Originally Posted by Shaggy Hiker View Post
    In either case, LINQ, such as MattP showed, is tight, elegant, and slower.
    Except that it took until the third post before the macro-optimisation of the early exit from the loop was introduced, but the LINQ version gives it to you for absolute free.

  11. #11
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: How to range an array?

    Quote Originally Posted by Flashbond View Post
    Ok. This seems awsome but I didn't get it completely. Can you give an example of usage of function with only one array, please?
    The Any function returns True if any item in the list satisfies the specified condition and False otherwise while the All function returns True if all items in the list satisfy the condition and False otherwise. The condition is specified in the form of a delegate, i.e. a reference to a function that can be passed each item in the list and will return a Boolean. If that function returns True for any item then Any returns True and if it returns True for all items then All returns True.

    Taking this line of code:
    Code:
    Dim isNotEvenlyDivisible1 = Not p1.Any(Function(p) p Mod m = 0)
    the highlighted part is called a Lambda Expression, which is basically an inline function. You could use a regular named function instead:
    Code:
    Private Function IsEvenlyDivisible(p As Integer) As Boolean
        Return p Mod m = 0
    End Function
    The highlighted parts are what is required when writing an equivalent lambda but the rest is inferred from the usage. The compiler knows that the function returns a Boolean because that's what Any and All expect and it knows the type of 'p' because it's the same as the type of the items in the list you call Any or All on. If you were to use that named function instead of the lambda then the code would look like this:
    Code:
    Dim isNotEvenlyDivisible1 = Not p1.Any(AddressOf IsEvenlyDivisible)
    That basically says "for each item in 'p1', call the function IsEvenlyDivisible and pass the item as an argument and if any of those calls return True then return True, otherwise return False". The lambda does the same thing but more succinctly, plus it makes it easier to get the value of 'm' in there.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  12. #12

    Thread Starter
    Fanatic Member Flashbond's Avatar
    Join Date
    Jan 2013
    Location
    Istanbul
    Posts
    646

    Re: How to range an array?

    jmcilhinney, I appreciate for your efforts but I couldn't figure out how to use this. I think this is a couple of levels up for me. It starts with Dim, OK. After giving the dimension you are identifying the function. Then, how may I use IsEvenlyDivisible function in the code? A sample please. And one more thing: Why we are using p1? What is the difference with p()? If you bored from me you don't have to answer but I am not good with coding and not that smart.

  13. #13
    PowerPoster Evil_Giraffe's Avatar
    Join Date
    Aug 2002
    Location
    Suffolk, UK
    Posts
    2,555

    Re: How to range an array?

    The first code snippet in jmc's post is separate from the second and third. The second code snippet defines the IsEvenlyDivisible function that does the same work as the lambda expression in the first snippet. The third snippet shows how to use that function in place of the lambda expression, instead of 'Function (p) p Mod m = 0' you write 'AddressOf IsEvenlyDivisible'. What this is doing is passing a 'bit of code' as a parameter, rather than passing some data. The Any() method is then able to execute that code internally.

  14. #14

    Thread Starter
    Fanatic Member Flashbond's Avatar
    Join Date
    Jan 2013
    Location
    Istanbul
    Posts
    646

    Re: How to range an array?

    Ok guys then, I think this much info must be enough for me. I'll work on them. Thanks a lot for all your efforts!!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width