RingDotNetfor Ring

Arrays

A Ring list can hold anything and grow, but many .NET methods want an array — a fixed size and one type. This lesson shows how arrays come and go between Ring and .NET, and uses Array.Sort, Reverse, IndexOf, BinarySearch, Copy and Clear and an array with two dimensions.

What you will learn#

The tutorial Collections and LINQ used lists and dictionaries, the tutorial Binary files used arrays of bytes and the tutorial More data structures other collections. Arrays are the base of all of them.

The program#

samples/UsingDotNet/tutorials/ch04_arrays.ring
# arrays - Ring lists and .NET arrays, Array.Sort, Reverse, IndexOf, BinarySearch, Copy and Clear, and arrays with two dimensions
load "dotnet.ring"

using {
	"System"
}

func main

	oArray = new Array()

	# 1. A .NET array has a fixed size and one type. A Ring list becomes an array when a method asks for one: the bridge makes an int[],
	#    string[] or double[] from the values of the list. An array that comes back is a DotNetObject: toList() makes a Ring list of it.
	aNumbers = [42,7,19,3,25]
	new Array().Sort(aNumbers)
	? "1. a list given to Array.Sort comes back unchanged: " + list2text(aNumbers) + "(the bridge sorted its own copy)"

	# 2. So to sort, reverse or search an array, make the array first: a List<Int32> filled with Add, and ToArray()
	oInts = makeIntArray([42,7,19,3,25])
	? nl + "2. an Int32 array of " + oInts.Length + " items: " + arrayText(oInts)
	new Array().Sort(oInts)
	? "   after Array.Sort:     " + arrayText(oInts)
	new Array().Reverse(oInts)
	? "   after Array.Reverse:  " + arrayText(oInts)

	# 3. Searching: IndexOf answers the position (0-based, as in .NET) or -1. BinarySearch is much faster, but the array must be
	#    SORTED; it answers a negative number (the complement of the place to insert) when the value is not there.
	new Array().Sort(oInts)
	? nl + "3. IndexOf(19) in the sorted array: " + new Array().IndexOf([ :array = oInts, :value = 19 ]) + "   (0-based: Ring would say 3)"
	? "   IndexOf(99): " + new Array().IndexOf([ :array = oInts, :value = 99 ])
	nFound = new Array().BinarySearch([ :array = oInts, :value = 19 ])
	nMissing = new Array().BinarySearch([ :array = oInts, :value = 20 ])
	? "   BinarySearch(19): " + nFound + ", BinarySearch(20): " + nMissing + "   (negative: not found; the complement " + (-nMissing - 1) + " is where 20 would go, 0-based)"

	# 4. Copy and Clear. Array.Copy(source, target, count) copies the first items into another array; Clear(array, start, count) sets items to zero
	oTarget = makeIntArray([0,0,0,0,0,0,0,0])
	new Array().Copy([ :sourceArray = oInts, :destinationArray = oTarget, :length = oInts.Length ])
	? nl + "4. copied into a bigger array: " + arrayText(oTarget)
	new Array().Clear([ :array = oTarget, :index = 0, :length = 3 ])
	? "   Array.Clear(array, 0, 3) sets 3 items to zero: " + arrayText(oTarget)

	# 5. An array of texts, and the join of a list into one text
	oWordList = new List([ :typeArguments = ["System.String"] ])
	for cWord in ["pear","apple","fig"]
		oWordList.Add(cWord)
	next
	oWords = oWordList.ToArray()
	new Array().Sort(oWords)
	? nl + "5. sorted words: " + arrayText(oWords)

	# 6. Two dimensions: a table with rows and columns. Array.CreateInstance(type, rows, columns); items are written with SetValue(value, row, column)
	#    and read with GetValue(row, column). The items are Doubles, because SetValue needs the type that a Ring number has.
	oGrid = new Array().CreateInstance([ :elementType = dnType("System.Double"), :length1 = 3, :length2 = 4 ])
	for nRow = 0 to 2
		for nColumn = 0 to 3
			oGrid.SetValue([ :value = nRow * 10 + nColumn, :index1 = nRow, :index2 = nColumn ])
		next
	next
	? nl + "6. a 3 x 4 table (rank " + oGrid.Rank + ", " + oGrid.Length + " items, " + oGrid.@GetLength(0) + " rows, " + oGrid.@GetLength(1) + " columns):"
	for nRow = 0 to 2
		cLine = "   "
		for nColumn = 0 to 3
			cLine += padLeft("" + oGrid.GetValue([ :index1 = nRow, :index2 = nColumn ]),4)
		next
		? cLine
	next

# A typed array is made from a list: add the values to a List<Int32> and call ToArray(). (Array.SetValue takes an object: a whole number is
# an Int32 there and fits an Int32 array, a number with a fraction is a Double and does not.)
func makeIntArray aList

	oList = new List([ :typeArguments = ["System.Int32"] ])
	for nValue in aList
		oList.Add(nValue)
	next
	return oList.ToArray()

func arrayText oArray

	cText = ""
	aItems = oArray.toList()
	for item in aItems
		cText += "" + item + " "
	next
	return cText

func list2text aList

	cText = ""
	for item in aList
		cText += "" + item + " "
	next
	return cText

func padLeft cText,nWidth

	return copy(" ",nWidth - len(cText)) + cText
Output
1. a list given to Array.Sort comes back unchanged: 42 7 19 3 25 (the bridge sorted its own copy)

2. an Int32 array of 5 items: 42 7 19 3 25 
   after Array.Sort:     3 7 19 25 42 
   after Array.Reverse:  42 25 19 7 3 

3. IndexOf(19) in the sorted array: 2   (0-based: Ring would say 3)
   IndexOf(99): -1
   BinarySearch(19): 2, BinarySearch(20): -4   (negative: not found; the complement 3 is where 20 would go, 0-based)

4. copied into a bigger array: 3 7 19 25 42 0 0 0 
   Array.Clear(array, 0, 3) sets 3 items to zero: 0 0 0 25 42 0 0 0 

5. sorted words: apple fig pear 

6. a 3 x 4 table (rank 2, 12 items, 3 rows, 4 columns):
      0   1   2   3
     10  11  12  13
     20  21  22  23
Note

This program uses a few generic functions (dnStatic, dnNewGeneric, dnType) where a class cannot be used. The lesson The generic functions explains them.

How it works#

Arrays and lists#

A .NET array has a fixed length and one type (int[], string[], double[]), so it is compact and fast and an array of numbers never holds a text. A Ring list can change size and hold any mix. When a method wants an array and you pass a list, the bridge makes an array from the values (an int[] for whole numbers, a string[] for texts) for that call only. The array that the method sorts or changes is a copy: in step 1 the Ring list is unchanged after Array.Sort. To work on an array you must have the array, as a .NET object.

Making an array#

The easy way is a typed list: a List<Int32> (made with dnNewGeneric), the values added with Add, and ToArray(). The result is a plain object (oInts) with Length, Rank (the number of dimensions), toList() to copy it into a Ring list, and the static Array methods. Array.CreateInstance(type, length) makes an empty array, but its SetValue(value, index) takes an object: a whole number is an Int32 there and fits an Int32 array, a number with a fraction is a Double and does not. The program fills its Int32 arrays from a list.

Array methods#

They are static methods of the Array class. Sort and Reverse are called on new Array() like any static method; for the others the program uses dnStatic("System.Array", method, [arguments]). These names have several forms, so as methods of an object each would take one list of named values; dnStatic names the class and the method as texts and passes the values in order:

CallDoes
Sort(array)sorts the array in place (numbers by value, texts by the culture, the tutorial Comparing text)
Reverse(array)turns the order round
IndexOf(array, value)the position of the first item that is equal, or -1
BinarySearch(array, value)the position in a sorted array, very fast; for a missing value a negative number
Copy(source, target, count)copies the first items into another array
Clear(array, start, count)sets items to zero (or empty)

Positions are zero-based: the first item of an array is at position 0, the first item of a Ring list at position 1. IndexOf(19) is 2 in the sorted array 3 7 19 25 42, where Ring says 3. Keep this in mind whenever a number goes between Ring and .NET.

BinarySearch#

Looking at every item takes a long time in a big array. BinarySearch looks at the middle, decides which half can hold the value and repeats: a million items need about 20 steps. It needs a sorted array; in an unsorted one the answer is wrong without any error. For a value that is not there, the result is negative: it is the bitwise complement of the place where the value would go, so -(result) - 1 gives the position for inserting it (20 would go at position 3). Test >= 0 for "found".

Two dimensions#

Array.CreateInstance(type, rows, columns) makes a table; its Rank is 2 and Length is the number of items (12). GetLength(0) is the number of rows and GetLength(1) the number of columns; in Ring the method is @GetLength(dimension), because the name clashes with the property Length (Core concepts). Items are written with SetValue([ :value = v, :index1 = row, :index2 = column ]) and read with GetValue([ :index1 = row, :index2 = column ]). For a table of Ring numbers it is often simpler to use a Ring list of lists; use a 2D array when a .NET method wants one.

What you learned#

Exercises#

  1. Write contains(oArray, value) with IndexOf.
  2. Fill an array with 100 000 random numbers (the tutorial Randomness), sort it and compare IndexOf and BinarySearch with a Stopwatch.
  3. Use BinarySearch to insert a value into a sorted list at the right place.
  4. Fill a 9 x 9 Double array with the multiplication table and print it.

Next#

Sets

RingDotNet — use .NET classes and methods from Ring programs. Screenshots and output on these pages come from the real samples.