Why does this recurring function fire twice per input? - recursion

When executing:
def guess(a..b) do
IO.puts "In rn = #{a}..#{b}"
guess(a..b, IO.getn("Is it greater than #{div(a + b, 2)} ? : ", 1) |> String.upcase == "Y")
end
def guess(a..b, true) do
guess(div(a + b, 2)..b)
end
def guess(a..b, false) do
guess(a..div(a + b, 2))
end
Results:
iex(1)> Test.guess(1..10)
1 In rn = 1..10
2 Is it greater than 5 ? : y
3 In rn = 5..10
4 Is it greater than 7 ? :
5 In rn = 5..7
6 Is it greater than 6 ? : n
7 In rn = 5..6
8 Is it greater than 5 ? :
9 In rn = 5..5
10 Is it greater than 5 ? : y
11 In rn = 5..5
12 Is it greater than 5 ? :
13 In rn = 5..5
14 Is it greater than 5 ? :
iex did not wait for user input on lines 4, 8, & 12 - after receiving an input, it appears to run through the loop twice.
Why might that be?
Solved:
Apparently, something weird happens with IO.getn when used in this manner - perhaps reading "Y" as a byte, and "enter" as a separate byte. Replacing IO.gets and no character count seems to fix the problem. Alternatively, isolating the getn method call might keep this issue from occurring.

You are correct. When in the terminal, IO.getn/1 only returns the bytes after you enter a new line, which means if you are reading byte per byte recursively, you are going to receive two bytes, one for the user command and another for the new line. IO.gets/1 is the way to go here.

Related

How do I finish a recursive binary search in fortran?

I am trying to find the smallest index containing the value i in a sorted array. If this i value is not present I want -1 to be returned. I am using a binary search recursive subroutine. The problem is that I can't really stop this recursion and I get lot of answers(one right and the rest wrong). And sometimes I get an error called "segmentation fault: 11" and I don't really get any results.
I've tried to delete this call random_number since I already have a sorted array in my main program, but it did not work.
program main
implicit none
integer, allocatable :: A(:)
real :: MAX_VALUE
integer :: i,j,n,s, low, high
real :: x
N= 10 !size of table
MAX_VALUE = 10
allocate(A(n))
s = 5 ! searched value
low = 1 ! lower limit
high = n ! highest limit
!generate random table of numbers (from 0 to 1000)
call Random_Seed
do i=1, N
call Random_Number(x) !returns random x >= 0 and <1
A(i)= anint(MAX_VALUE*x)
end do
call bubble(n,a)
print *,' '
write(*,10) (a(i),i=1,N)
10 format(10i6)
call bsearch(A,n,s,low,high)
deallocate(A)
end program main
The sort subroutine:
subroutine sort(p,q)
implicit none
integer(kind=4), intent(inout) :: p, q
integer(kind=4) :: temp
if (p>q) then
temp = p
p = q
q = temp
end if
return
end subroutine sort
The bubble subroutine:
subroutine bubble(n,arr)
implicit none
integer(kind=4), intent(inout) :: n
integer(kind=4), intent(inout) :: arr(n)
integer(kind=4) :: sorted(n)
integer :: i,j
do i=1, n
do j=n, i+1, -1
call sort(arr(j-1), arr(j))
end do
end do
return
end subroutine bubble
recursive subroutine bsearch(b,n,i,low,high)
implicit none
integer(kind=4) :: b(n)
integer(kind=4) :: low, high
integer(kind=4) :: i,j,x,idx,n
real(kind=4) :: r
idx = -1
call random_Number(r)
x = low + anint((high - low)*r)
if (b(x).lt.i) then
low = x + 1
call bsearch(b,n,i,low,high)
else if (b(x).gt.i) then
high = x - 1
call bsearch(b,n,i,low,high)
else
do j = low, high
if (b(j).eq.i) then
idx = j
exit
end if
end do
end if
! Stop if high = low
if (low.eq.high) then
return
end if
print*, i, 'found at index ', idx
return
end subroutine bsearch
The goal is to get the same results as my linear search. But I'am getting either of these answers.
Sorted table:
1 1 2 4 5 5 6 7 8 10
5 found at index 5
5 found at index -1
5 found at index -1
or if the value is not found
2 2 3 4 4 6 6 7 8 8
Segmentation fault: 11
There are a two issues causing your recursive search routine bsearch to either stop with unwanted output, or result in a segmentation fault. Simply following the execution logic of your program at the hand of the examples you provided, elucidate the matter:
1) value present and found, unwanted output
First, consider the first example where array b contains the value i=5 you are searching for (value and index pointed out with || in the first two lines of the code block below). Using the notation Rn to indicate the the n'th level of recursion, L and H for the lower- and upper bounds and x for the current index estimate, a given run of your code could look something like this:
b(x): 1 1 2 4 |5| 5 6 7 8 10
x: 1 2 3 4 |5| 6 7 8 9 10
R0: L x H
R1: Lx H
R2: L x H
5 found at index 5
5 found at index -1
5 found at index -1
In R0 and R1, the tests b(x).lt.i and b(x).gt.i in bsearch work as intended to reduce the search interval. In R2 the do-loop in the else branch is executed, idx is assigned the correct value and this is printed - as intended. However, a return statement is now encountered which will return control to the calling program unit - in this case that is first R1(!) where execution will resume after the if-else if-else block, thus printing a message to screen with the initial value of idx=-1. The same happens upon returning from R0 to the main program. This explains the (unwanted) output you see.
2) value not present, segmentation fault
Secondly, consider the example resulting in a segmentation fault. Using the same notation as before, a possible run could look like this:
b(x): 2 2 3 4 4 6 6 7 8 8
x: 1 2 3 4 5 6 7 8 9 10
R0: L x H
R1: L x H
R2: L x H
R3: LxH
R4: H xL
.
.
.
Segmentation fault: 11
In R0 to R2 the search interval is again reduced as intended. However, in R3 the logic fails. Since the search value i is not present in array b, one of the .lt. or .gt. tests will always evaluate to .true., meaning that the test for low .eq. high to terminate a search is never reached. From this point onwards, the logic is no longer valid (e.g. high can be smaller than low) and the code will continue deepening the level of recursion until the call stack gets too big and a segmentation fault occurs.
These explained the main logical flaws in the code. A possible inefficiency is the use of a do-loop to find the lowest index containing a searched for value. Consider a case where the value you are looking for is e.g. i=8, and that it appears in the last position in your array, as below. Assume further that by chance, the first guess for its position is x = high. This implies that your code will immediately branch to the do-loop, where in effect a linear search is done of very nearly the entire array, to find the final result idx=9. Although correct, the intended binary search rather becomes a linear search, which could result in reduced performance.
b(x): 2 2 3 4 4 6 6 7 |8| 8
x: 1 2 3 4 5 6 7 8 |9| 10
R0: L xH
8 found at index 9
Fixing the problems
At the very least, you should move the low .eq. high test to the start of the bsearch routine, so that recursion stops before invalid bounds can be defined (you then need an additional test to see if the search value was found or not). Also, notify about a successful search right after it occurs, i.e. after the equality test in your do-loop, or the additional test just mentioned. This still does not address the inefficiency of a possible linear search.
All taken into account, you are probably better off reading up on algorithms for finding a "leftmost" index (e.g. on Wikipedia or look at a tried and tested implementation - both examples here use iteration instead of recursion, perhaps another improvement, but the same principles apply) and adapt that to Fortran, which could look something like this (only showing new code, ...refer to existing code in your examples):
module mod_search
implicit none
contains
! Function that uses recursive binary search to look for `key` in an
! ordered `array`. Returns the array index of the leftmost occurrence
! of `key` if present in `array`, and -1 otherwise
function search_ordered (array, key) result (idx)
integer, intent(in) :: array(:)
integer, intent(in) :: key
integer :: idx
! find left most array index that could possibly hold `key`
idx = binary_search_left(1, size(array))
! if `key` is not found, return -1
if (array(idx) /= key) then
idx = -1
end if
contains
! function for recursive reduction of search interval
recursive function binary_search_left(low, high) result(idx)
integer, intent(in) :: low, high
integer :: idx
real :: r
if (high <= low ) then
! found lowest possible index where target could be
idx = low
else
! new guess
call random_number(r)
idx = low + floor((high - low)*r)
! alternative: idx = low + (high - low) / 2
if (array(idx) < key) then
! continue looking to the right of current guess
idx = binary_search_left(idx + 1, high)
else
! continue looking to the left of current guess (inclusive)
idx = binary_search_left(low, idx)
end if
end if
end function binary_search_left
end function search_ordered
! Move your routines into a module
subroutine sort(p,q)
...
end subroutine sort
subroutine bubble(n,arr)
...
end subroutine bubble
end module mod_search
! your main program
program main
use mod_search, only : search_ordered, sort, bubble ! <---- use routines from module like so
implicit none
...
! Replace your call to bsearch() with the following:
! call bsearch(A,n,s,low,high)
i = search_ordered(A, s)
if (i /= -1) then
print *, s, 'found at index ', i
else
print *, s, 'not found!'
end if
...
end program main
Finally, depending on your actual use case, you could also just consider using the Fortran intrinsic procedure minloc saving you the trouble of implementing all this functionality yourself. In this case, it can be done by making the following modification in your main program:
! i = search_ordered(a, s) ! <---- comment out this line
j = minloc(abs(a-s), dim=1) ! <---- replace with these two
i = merge(j, -1, a(j) == s)
where j returned from minloc will be the lowest index in the array a where s may be found, and merge is used to return j when a(j) == s and -1 otherwise.

Dynamic Triple N Step

I am working on the problem from Cracking the Coding Interview:
A child is running up a staircase with n steps, and can hop either 1 step, 2 steps, or 3 steps at a time.
Implement a method to count how many possible ways the child can run up the stairs.
I came up with a dynamic solution:
def dynamic_prog(N):
store_values = {1:1,2:2,3:3}
return dynamic_prog_helper(N, store_values)
def dynamic_prog_helper(N, map_n):
if N in map_n:
return map_n[N]
map_n[N] = dynamic_prog_helper(N-1, map_n) + dynamic_prog_helper(N-2, map_n) + dynamic_prog_helper(N-3,map_n)
return map_n[N]
I am not sure why it does not compute correctly.
dynamic_prog(5) = 11, but should be 13
dynamic_prog(4) = 6, but should be 7
Can someone point me in the right direction?
The critical problem is that your initial value for store_values[3] is wrong. From 3 steps down, you have 4 possibilities:
3
2 1
1 2
1 1 1
Fixing that error gets the expected results:
def dynamic_prog(N):
store_values = {1:1,2:2,3:4}
return dynamic_prog_helper(N, store_values)
...
for stair_count in range(3, 6):
print dynamic_prog(stair_count)
Output:
4
7
13

How to filter package content in wireshark?

I am filtering package in Wireshark(version 2.0.3),the tcp package data is like this:
7e:02:00:00:3c:01:41:31:07:17:83:02:97:00:00:00:00:00:0c:00:c3:02:28:ba:50:06:f1:ec:c0:00:59:00:00:01:2e:16:06:30:10:46:00:01:04:00:00:e6:2f:02:02:00:00:03:02:00:00:25:04:00:00:00:00:2b:04:00:00:00:00:30:01:13:31:01:12:5e:7e
Now I want to find the third byte to four byte contains 00:00,how to write the filter expression? I have tried:
ip[3,2] == 00:00 #in tcpdump it works
data.data[3,2] == 00:00 #data.data == 00:00,but data not just only contain:00:00
Any solution?
The count starts from 0 so you are looking for 2 and 3 in your example.
You can specify and group slices (what you're doing in your example), or provide a range.
# Combines 2 slices
frame[2,3]==0000
# From byte position 2 include 2 bytes (e.g. 2 and 3)
frame[2:2]==0000
# Provides byte range 2 through 3
frame[2-3]==0000
The following syntax governs slices:
Source: https://www.wireshark.org/docs/man-pages/wireshark-filter.html
[i:j] i = start_offset, j = length
[i-j] i = start_offset, j = end_offset, inclusive.
[i] i = start_offset, length = 1
[:j] start_offset = 0, length = j
[i:] start_offset = i, end_offset = end_of_field
Using this filter:
data[3:2] == 00:00 # start from 22,get 2 byte equal to 00:00

VB: how to get the index(es) of an array element if used in For Each

i have the following VB Script written in an .asp file
Dim myArr(5, 6) '// a 6 * 7 array
For i = LBound(myArr, 1) to UBound(myArr, 1)
For j = LBound(myArr, 1) to UBound(myArr, 1)
myArr(i, j) = "i:" & i & ", j:" & j
next
next
Dim i
i = 0
For Each k In myArr
Response.Write("i:" & i ", k:" & k & "<br>")
i = i + 1
Next
using For Each i can iterate through all the array items,
and the question is how can i get the index for each dimension ?
for example: how can i get k index after 10th loop that is 2 and 4 ?
Useful info number 1
First of consider this bit of VBS:
Option Explicit
Dim aaa(1,1,1)
Dim s : s = ""
Dim i, j, k
For i = LBound(aaa, 3) To UBound(aaa, 3)
For j = LBound(aaa, 2) To UBound(aaa, 2)
For k = LBound(aaa, 1) To UBound(aaa, 1)
aaa(k, j, i) = 4 * i + 2 * j + k
Next
Next
Next
Dim x
For Each x in aaa
s = s + CStr(x) + " : "
Next
MsgBox s
This returns "0 : 1 : 2 : 3 : 4 : 5 : 6 : 7 :" which looks good, but note the order of indexers in the inner assignment aaa(k, j, i). If we were to use the more natural aaa(i, j, k) we'd see what appears to us to be a jubbled order returned. Thats because we assume that the left most indexer is the most significant but it isn't its the least significant.
Where bounds start at 0 then for the first dimension all the values in index 0..N are held contigiously where the other dimensions are 0. Then with the next dimension at 1, the next set of 0..N members of the first dimension follow and so on.
Useful info number 2
Given an array of unknown number of dimensions the following code returns the count of dimensions:
Function GetNumberOfDimensions(arr)
On Error Resume Next
Dim i
For i = 1 To 60000
LBound arr, i
If Err.Number <> 0 Then
GetNumberOfDimensions = i - 1
Exit For
End If
Next
End Function
Solution
Given an array construct like this.
Dim arr(3,3,3)
Dim s : s = ""
Dim i, j, k
For i = LBound(arr, 3) To UBound(arr, 3)
For j = LBound(arr, 2) To UBound(arr, 2)
For k = LBound(arr, 1) To UBound(arr, 1)
arr(k, j, i) = 16 * i + 4 * j + k
Next
Next
Next
Here is some code that is able to determine the set of indices for each item in an array of arbitary dimensions and sizes.
Dim dimCount : dimCount = GetNumberOfDimensions(arr)
Redim dimSizes(dimCount - 1)
For i = 1 To dimCount
dimSizes(i - 1) = UBound(arr, i) - LBound(arr, i) + 1
Next
Dim index : index = 0
Dim item
For Each item in arr
s = "("
Dim indexValue, dimIndex
indexValue = index
For dimIndex = 0 To dimCount - 1
s = s + CStr((indexValue mod dimSizes(dimIndex)) - LBound(arr, dimIndex + 1)) + ", "
indexValue = indexValue \ dimSizes(dimIndex)
Next
Response.Write Left(s, Len(s) - 2) + ") = " + Cstr(item) + "<br />"
index = index + 1
Next
An interesting acedemic exercise, not sure how useful it is.
You can't. For each is defined to iterate over objects without having to know the amount of objects (as defined in the IEnumerable interface) at the moment the next object is returned (making multithreading possible).
It is also not specified that you'll receive your objects in exact the same order as you put them (although, I never experienced an other order for arrays), that depends on the Enumerator Interface object that is specified for the collection.
Fortunately, there are other tricks to do what you want, but the implementation depends on the problem you are trying to solve.
For example, you can use an array with arrays, the ArrayList class from System.Collections.ArrayList or create an own class where you store your values or objects.
Please note: There are some discussions about this correctness of this answer, see the comments below. I'll study the subject and will share any relevant experiences I got from them.
You could create a helper object like this:
Option Explicit
dim myArr(5,6)
dim i, j, k
For i = LBound(myArr, 1) to UBound(myArr, 1)
For j = LBound(myArr, 2) to UBound(myArr, 2)
Set myArr(i, j) = [new LookupObject]("i:" & i & ", j:" & j, i, j)
next
next
For Each k In myArr
Response.Write("This is k:" & k & "<br>")
Response.Write("i index of k: " & k.I & "<br>")
Response.Write("j index of k: " & k.J & "<br>")
Next
Public Function [new LookupObject](value, i, j)
Set [new LookupObject] = (new cls_LookupObject).Init(value, i, j)
End Function
Class cls_LookupObject
Private value_, i_, j_
Public Function Init(value, i, j)
i_ = i
j_ = j
value_ = value
Set Init = me
End Function
Public Default Property Get Value()
Value = value_
End Property
Public Property Get I()
I = i_
End Property
Public Property Get J()
J = j_
End Property
End Class
DISCLAIMER: As I created this code on a non Windows machine, I couldn't test it. You could find some syntax or design errors. The naming is not very great, but this way it sticks more to your concept.
Although, it seems you are searching for a simple solution. Not one that will introduce more 'challenges': When you want to pass around values in the array that keep their internal indices, you need to Set them instead of just assigning them: this decreases portability.
And when you use objects, you need to know how Object References work in contrast to primitives, otherwise you'll get some unexpected behavior of values changing when you don't expected it.
UPDATED
If a person interested in how VBScript compares to other languages with regard
to arrays, foreach looping, and especially obtaining information about the
position of the element delivered by "For Each" in the collection looped over,
would pose a question like:
How does VBScript compare to other languages with regard to arrays,
foreach looping, and especially obtaining information about the
position of the element delivered by "For Each" in the collection
looped over?
then a short answer would have been available long ago:
A foreach loop construct can deliver
a pointer (memory address) - as e.g. C/C++ does; then you have to
de-reference the pointer to get at the element which you can even
change; positional info is optainable by pointer arithmetic)
a reference (alias) (as e.g. Perl does; that allows modification,
but obviously no computing of positions (unless the element
accidentially contains such info))
a copy (as e.g. Python or VBScript do; neither modification nor
retrieval of meta info is possible (unless some kind and clever
souls like AutomatedChaos or AnthonyWJones work their heart out to
implement a C/C++ alike solution by submitting a loop variable to
DIVs and MODs resp. to design a class that allows to augment the
plain/essential data values with meta info)
You may safely ignore the rest of my answer; I just don't want to delete the
following text which provides some context for the discussion.
The problem can't be dealt with, until
(1) armen describes the context of the real world problem in real world terms - where do the arrays come from, how many dimensions are possible, what determines the dimensional
structure (row/column/...), which operations must be done in the For Each loop, why/how are the indices important for these operations
(2) all contributors get their selectors for the dimensions right:
For i = LBound(myArr, 1) to UBound(myArr, 1)
For j = LBound(myArr, 1) to UBound(myArr, 1)
or variations thereof are obviously wrong/misleading. Without replacing the 1 in one line by 2, it's not clear, what row/column-structure the code is meant for.
To prove that I'm willing to contribute in a more constructive way, I throw in a function to get the (number of) dimensions for an arbitrary array:
Function getDimensions(aVBS)
Dim d : d = 0
If IsArray(aVBS) Then
For d = 1 To 60
On Error Resume Next
UBound aVBS, d + 1
If Err.Number Then Exit For
On Error GoTo 0
Next
End If
getDimensions = d
End Function ' getDimensions
(based on code by M. Harris and info from the VBScript Docs)
Update: Still not a solution, but some food for thought
As armen (upto now) didn't provide the real story of his problem, I try to
give you a fictonal one (to put a context to the rows and columns and whatever
you may call the thingies in the third dimension):
Let's say there is a school - Hogmond - teaching magical programming. VBScript
is easy (but in the doghouse), so there are just three tests and students are
admitted mid term (every penny counts). JScript is harder, so you have to do the
full course and additional tests may be sheduled during the term, if pupils
prove thick. F# is more complicated, so each test has to be judged in terms of
multiple criteria, some of which may be be agreed upon during the term (the
teachers are still learning). C# is such a 'good' language, that there is just
one test.
So at the end of the term the principal - Mr. Bill 'Sauron' Stumblegates - has
an .xls, containing a sheet:
(Doreen was accepted during the last week of the term) and a sheet:
(for your peace of mind, 120 additional tests are hidden); the F# results
are kept in a .txt file:
# Results of the F# tests
# 2 (fixed) students, 3 (fixed) test,
# 4>5 (dynamic) criteria for each test
Students Ann Bill
Test TA TB TC TA TB TC
Criteria
CA 1 2 3 4 5 6
CB 7 8 9 10 11 12
CC 13 14 15 16 17 18
CD 19 20 21 22 23 24
# CE 25 26 27 28 29 30
(because I know nothing about handling three+-dimensional data in Excel).
Now we have a context to think about
data: it's important that Mary scored 9 for the eval test, but
whether that info is stored in row 5 or 96 is not an inherent
property of the data [Implies that you should think twice before you
embark on the (taken by itself: impressive) idea of AutomatedChaos
to create objects that combine (essential) data and (accidential)
info about positions in a (n arbitrary) structure.]
processing: some computations - especially those that involve the
whole dataset - can be done with no regard to rows or colums (e.g.
average of all scores); some may even require a
restructuring/reordering (e.g. median of all scores); many
computations - all that involve selection/grouping/subsets of the
data - just can't be done without intimate knowledge about the
positions of the data items. armen, however, may not be interested
in processing at all - perhaps all he needs the indices for is to
identify the elements while displaying them. [So it's futile to
speculate about questions like "Shouldn't Excel/the database do the
processing?", "Will the reader be content with 'D5: 9' or does he
whish to see 'Mary/eval: 9' - and would such info be a better
candidate for AutomatedChaos' class?", "What good is a general 'For
Each' based function/sub that handles arrays of every dimension, if
assignments - a(i)=, b(i,j)=, c(i,j,k)= ... - can't be
parameterized?"]
structure/layout: the choice of how you put your data into rows and
columns is determined by convenience (vertical scrolling perfered),
practical considerations (append new data 'at the end'), and
technical reasons (VBScript's 'ReDim Preserve' can grow (dynamic)
arrays in the last dimension only) - so for each layout that makes
sense for a given context/task there are many other structures that
are better in other circumstances (or even the first context).
Certainly there is no 'natural order of indexers'.
Now most programmers love writing/written code more than reading stories (and
some more than to think about/plan/design code), so here is just one example
to show what different beasts (arrays, 'iterators') our pipe dream/magical
one-fits-all-dimensions 'For Each' strategy has to cope with:
Given two functions that let you cut data from Excel sheets:
Function getXlsRange(sSheet, sRange)
Dim oX : Set oX = CreateObject("Excel.Application")
Dim oW : Set oW = oX.Workbooks.Open(resolvePath("..\data\hogmond.xls"))
getXlsRange = oW.Sheets(sSheet).Range(sRange).Value
oW.Close
oX.Quit
End Function ' getXlsRange
Function getAdoRows(sSQL)
Dim oX : Set oX = CreateObject("ADODB.Connection")
oX.open Join(Array( _
"Provider=Microsoft.Jet.OLEDB.4.0" _
, "Data Source=" & resolvePath("..\data\hogmond.xls") _
, "Extended Properties=""" _
& Join(Array( _
"Excel 8.0" _
, "HDR=No" _
, "IMEX=1" _
), ";" ) _
& """" _
), ";")
getAdoRows = oX.Execute(sSQL).GetRows()
oX.Close
End Function ' getAdoRows
(roll your own resolvePath() function or hard code the file spec)
and a display Sub (that uses armen's very good idea to introduce a
loop counter variable):
Sub showAFE(sTitle, aX)
Dim i, e
WScript.Echo "For Each:", sTitle
WScript.Echo "type:", VarType(aX), TypeName(aX)
WScript.Echo "dims:", getDimensions(aX)
WScript.Echo "lb :", LBound(aX, 1), LBound(aX, 2)
WScript.Echo "ub :", UBound(aX, 1), UBound(aX, 2)
WScript.Echo "s :", UBound(aX, 1) - LBound(aX, 1) + 1 _
, UBound(aX, 2) - LBound(aX, 2) + 1
i = 0
For Each e In aX
WScript.Echo i & ":", e
i = i + 1
Next
End Sub ' showAFE
you can use code like
showAFE "VTA according to XlsRange:", getXlsRange("VTA", "B3:D4")
showAFE "VTA according to AdoRows:", getAdoRows("SELECT * FROM [VTA$B3:D4]")
to get your surprise of the weekend:
For Each: VTA according to XlsRange:
type: 8204 Variant()
dims: 2
lb : 1 1
ub : 2 3
s : 2 3
0: 1
1: 2
2: 3
3: 4
4: 5
5: 6
For Each: VTA according to AdoRows:
type: 8204 Variant()
dims: 2
lb : 0 0
ub : 2 1
s : 3 2
0: 1
1: 3
2: 5
3: 2
4: 4
5: 6
and despair:
Mr. Stumblegates type system hides the fact that these two arrays
have a very different nature (and the difference between fixed and
dynamic arrays is ignored too)
You can create all kinds of arrays in VBScript as long as they are
zero-based (no chance of creating and/or restructuring Range-born
arrays and keep their (accidential!) one-based-ness)
Getting one set of data with (necessarily) one layout via two
different methods will deliver the data with two different
structures
If you ask "For Each" to enumerate the data, the sequence you get is
determined by the iterator and not predictable (you have to
check/experiment). (Accentuating the freedom/role of the iterator is
the one nugget in AutomatedChaos' first answer)
[Don't read this, if you aren't interested in/can't stand a pedantic diatribe:
which still has a better score than AnthonyWJones' contribution, because at
least one person who admittedly has anderstood neither question nor answer
upvotes it, because of the reference to .ArrayList - which isn't relevant at all
to armen's question, because there is no way to make an ArrayList
multi-dimensional (i.e.: accessible by the equivalent of al(1,2,3)). Yes
"IEnumerable" (a pure .NET concept) and "multithread" are impressive keywords
and there are 'live' collections (e.g. oFolder.Files) that reflect 'on the fly'
modifications, but no amount of (single!)-threading will let you modify a humble
VBScript array while you loop - Mr. Stumblegates is a harsh master:
Dim a : a = Array(1, 2, 3)
Dim e
WScript.Stdout.WriteLine "no problem looping over (" & Join(a, ", ") & ")"
For Each e In a
WScript.Stdout.Write " " & e
Next
ReDim Preserve a(UBound(a) + 1)
a(UBound(a)) = 4
WScript.Stdout.WriteLine
WScript.Stdout.WriteLine "no problem growing the (dynamic) array (" & Join(a, ", ") & ")"
WScript.Stdout.WriteLine "trying to grow in loop"
For Each e In a
WScript.Stdout.Write " " & e
If e = 3 Then
On Error Resume Next
ReDim Preserve a(UBound(a) + 1)
If Err.Number Then WScript.Stdout.Write " " & Err.Description
On Error GoTo 0
a(UBound(a)) = 5
End If
Next
WScript.Stdout.WriteLine
output:
no problem looping over (1, 2, 3)
1 2 3
no problem growing the (dynamic) array (1, 2, 3, 4)
trying to grow in loop
1 2 3 This array is fixed or temporarily locked 5
Another elaboration of a blanket statement: Even good programmers make mistakes,
especially if they are eager to help, have to work under unfavorable conditions
(Mr. Stumblegates did his utmost to make sure that you can't use/publish VBScript
code without extensive testing), have a job and a live, or just a bad moment.
This, however, does not change the fact that some code fragments/statements are
useless or even dangerous to SO readers who - because of votes - think they have
found a solution to their problem. Quality of code/text is an essential property
of the content alone, who wrote it is just accidential. But how to be 'objective'
in a context where "Jon Doe's code" is the natural way to refer to lines like
for i = 0 to ubound(myArr)
for y = 0 to ubound(myArr, 1)
[UBound(a) and UBound(a, 1) are synonyms, so this will create havoc as soon
as the UBounds of the different dimensions are not (accidentially) the same]
and votes for content are summed up under the reputations of persons? (Would SO
list millions of answers without the reputation system? Would I put less time/work
in my contributions without the points? I hope/guess not, but I'm a human too.)
So I encourage you to downvote this elaborate (at least) until I correct the
limit of 60 in my getDimensions() function. You can't hurt my feelings; I think
I'm blameless, because all I did was to rely on the docs:
Dimensions of an array variable; up to 60 multiple dimensions may be
declared.
(What I'm a bit ashamed of is that I had feelings of superiority, when I looked
at the 999 or the 60000 in other people's code - as I said: I'm only human too;
and: Don't put your trust in Mr. Stumblegates, but check:
Dim nDim
For Each nDim In Array(3, 59, 60, 62, 64, 65, 70)
ReDim aDim(nDim)
Dim sDim : sDim = "ReDim a" & nDim & "(" & Mid(Join(aDim, ",0"), 2) & ")"
WScript.Echo sDim
On Error Resume Next
Execute sDim
If Err.Number Then WScript.Echo Err.Description
On Error GoTo 0
Next
output:
ReDim a3(0,0,0)
...
ReDim a64(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0)
ReDim a65(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)
Subscript out of range
...
)
Not to conclude in destructive mode: I still hope that my harping on the topic
"bounds used in nested loops to specify indexers (especially such of different
ranges)" will magically cause a lot of code lines here to be changed in the near
future - or aren't we all students at Hogmond?
]
Use nested For loops, instead of For Each
for i = 0 to ubound(myArr)
for y = 0 to ubound(myArr, 2)
' do something here...
next
next

Can Do While Loop stop when counter reaches X

I want to edit some legacy code written in classic-ASP.
Currently I've got a subroutine declared that uses a for-next loop to output some radio buttons:
For i = 1 to Cols
response.write "blah"
...
Next
i is simply a counter, Cols is a value passed to the sub-routine. I tried editing the for-loop to be a while loop instead:
i = Start
do while i <= Cols
response.write "blah"
...
i = i + 1
loop
But I get a Response Buffer Limit Exceeded error. If I replace Cols with the value it works fine. Is this a limitation in classic-ASP?
Reason I want to use a do while loop is because currently the sub-routine is limited to looping from 1 to Cols. It would be helpful to sometimes specify the loop counts backwards (i.e. step -1) but I can't write:
if Direction = Backwards then
For i = Cols to 1 step -1
else
For i = 1 to Cols
end if
How about:
If Direction = Backwards Then
cs = 10
ce = 1
s = -1
Else
cs = 1
ce = 10
s = 1
End If
For i = cs To ce Step s
''
Next

Resources