Looping through an array in Q# - quantum-computing

How to loop through the elements of an array and access them by their index in Q# language since the conventional looping in C++ doesn't work here.

Suppose the array is arr = T[], where T is any type in Q#.
let n = Length(arr);
for (i in 0 .. (n-1)) {
// use the element arr[i]
}
It is to be noted that if arr is defined using 'let' then the values are immutable and can be accessed but not assigned. If it is defined using 'mutable' literal then the elements can also be set using the 'set' keyword. In that case define the array is follows
mutable arr = new T[N]
where N is the length required.

Related

Create Two dimensional Array of Arrays with two variable types in Swift

You can create a two dimensional array of one type of variable in swift with:
var array2D: [[String]] = [["hi", "bye"], ["hello", "goodbye"]]
I want to create a two dimensional array with the second variable a Float along the following lines:
var array2d2types = [[String,Float]] = [["height",1],["width",2]]
But this gives error: Cannot assign to immutable expression of type '[[Any]]'
How can I create an array of arrays each of which has a String and a Float?
Swift arrays are homogeneous, so you cannot store different typed elements in the same array. However, you can achieve your goals using an array of tuples instead of nested arrays.
let array: [(String,Float)] = [("height",1),("width",2)]
You can access the tuples using the normal subscript syntax
let firstTuple = array[0]
and the elements of the tuple using dot syntax
let height = firstTuple.0
let heightValue = firstTuple.1
However, you should use a custom struct or even better the built-in CGSize for storing height-width values.
You should use a custom struct if you want to store various types. This has the added benefit of allowing you to access those values with a meaningful name instead of just an index. Use an array of tuples and .map(Record.init) to initializes the array of structures.
struct Record {
var string: String
var float: Float
}
var records = [("height", 1), ("width", 2)].map(Record.init)
print(records[0].string) // "height"
print(records[0].float) // 1.0

Dynamic arrays vs Variable-length arrays

What is the differences between Dynamic Arrays and Variable-length Arrays?
There are two separate sheets in Wikipedia about this:
1) Regarding Dynamic arrays:
https://en.wikipedia.org/wiki/Dynamic_array
2) Regarding Variable-length Arrays:
https://en.wikipedia.org/wiki/Variable-length_array
But it is not very clear the differences.
Could you give an example in some programming language the Dynamic Array which is not Variable-length one and vice versa.
There are four kind of arrays:
1) Dynamic Arrays
2) Variable-length Arrays
3) Fixed-length Array
4) Static array
Let's consider the four arrays in more details.
1) Dynamic array
In this case there is an API in array which alter length variable.
It can be a method that directly modifies the length
setSize(int newLength)
or a methods that modify it indirrectly:
add(Object newElement)
remove(Object toBeRemoved)
Both of these methods modify the length after adding/removing an element.
Example in Java that emulates Dynamic array:
java.util.ArrayList
2) Variable-length array
Variable-length array is a special case of Dynamic array.
In this case length is read-only and there is no API in array which modifies this variable.
But this variable can be changed by the system the other ways.
Example in Java that emulates Variable-length array - regular java arrays like int[].
Lets consider the example:
int[] a = new int[5]; System.out.println(a.length);
a = new int[10]; System.out.println(a.length);
In this case length variable is changed but we cannot modify it directly like
a.length = 20;
3) Fixed-length array
Fixed-length array is a special case of Variable-length array.
In this case once assigned a value to the length, we cannot modify it anymore.
But it is important to note that length variable is still determined at runtime
Example in Java that emulates this behaviour: final array variables like final int[].
Lets consider the example:
final int[] a;
if (someVar > 0) { a = new int[100]; } else { a = new int[200]; }
In this case a.length is either 100 or 200 and still determined at runtime.
4) Static array
Static array is a special case of Fixed-length array.
In this case length not only can be changed but also can be determined at runtime.
Example of such array in Java can be the following construction:
{1, 2, 3, 100, 200, 500}
This constuction can be assigned to a variable only while its initialization
int[] a = {1, 2, 3};
But if we try reassignment like
a = {1, 2};
we get compilation error.
Example in Java that emulates such an array:
final int[] a = {1, 2, 3};
Variable-length arrays have variable sizes that are set once during runtime.
Dynamic arrays are also variable length arrays, but they can also re-size (re-dimension) after they are created. This allows the array to grow to accommodate additional elements above its original capacity. If using an array, you would have to manually resize the array or overwrite existing data.
For example in C#, arrays (like int[]) are variable-length arrays. Lists (like List<int> or ArrayList) are a dynamically re-sizing arrays. A list hides some of the re-sizing in its .Add() method so the developer doesn't have to worry about it on their own.

AS3 - Assigning array2's variables to array1's

I'm trying to assign array2 to array1 by using: array2 = array1, but the problem is, and as it's mentioned here: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Array.html
Array assignment is by reference rather than by value. When you assign one array variable to another array variable, both refer to the same array
I thought of using a for-loop, and it worked perfectly, but I feel like there must be faster and more simple.
Here's my loop, if anyone's interested:
for (var n:int = 0; n < array1.length; n++)
{
array2[n] = array1[n];
}
So, I was wondering, Is there a way to assign array2 to array1 without using a loop?
You can use the slice method:
Returns a new array that consists of a range of elements from the
original array, without modifying the original array. The returned
array includes the startIndex element and all elements up to, but not
including, the endIndex element.
//default values of the parameters will return a copy of the array
array2 = array1.slice();

OCaml: Dynamic Arrays?

I've been trying to figure out how to resize an already initialized array in OCaml. However, it seems that while you can write a function that will create a brand new array with the elements of the old one copied over (and extra slots), that function's output cannot be assigned to existing array. How would one do this? Is there an easy way in which to use references to make this happen if not without?
Here's a tiny example:
let rec function_that_adds_to_array storage args ... =
(* let's say the function has a set of if-else constructs that controls what it does, and let's further say that one of the cases leads to: *)
let new_array = Array.make (Array.length storage) ("Null", ("Null", -2)) in
Array.blit collection 0 new_array 0 index; (* index is controlled by the function's recursion *)
Array.set new_array index (obj_name, obj_expr);
new_array) (* insert the macro at tail *)
...
;;
### main method ###
let storage = Array.make 10 ((x : string), (a, b)) in
...
while true do
...
storage = function_that_adds_to_array storage args....;
...
A print statement at the end of the function_that_adds_to_array(...) confirms that a new array is returned, containing the old elements of the initial array, however, in the main method, storage remains identical. Is this because of the immutability of OCaml's elements? I thought Arrays were mutable. I've looked around, and some mention writing hacks to getting OCaml to act like Perl, however, using one individual's resize hack function proved futile. Any way I can get storage to become a new array? It needs to be an update-able collection of tuples (i.e. (string, (x, y)) )?
In OCaml you can't assign to variables, period. There's no special limitation for arrays. However, you can have a variable that is bound to a reference, which can hold different values of the same type. This structure is what is usually called a "variable" in imperative languages. To have different sized arrays in a variable x you could write code as follows:
# let x = ref [| 0 |];;
val x : int array ref = {contents = [|0|]}
# Array.length x;;
Error: This expression has type int array ref
but an expression was expected of type 'a array
# Array.length !x;;
- : int = 1
# x := [| 2; 3 |];;
- : unit = ()
# Array.length !x;;
- : int = 2
The ! operator dereferences a reference, and the := operator assigns a new value.
If you're new to OCaml I'll include my standard advice that you should investigate the use of immutable data before deciding to recreate the patterns of imperative languages that you already know. If you're not new to OCaml, I apologize for my impertinence!

Array and slice data types

I found myself confused with the array and slice data types.
From Go docs, arrays are described as follows:
There are major differences between the ways arrays work in Go and C. In Go,
Arrays are values. Assigning one array to another copies all the elements.
In particular, if you pass an array to a function, it will receive a copy of the array, not a pointer to it.
The size of an array is part of its type. The types [10]int and [20]int are distinct.
Functions:
As in all languages in the C family, everything in Go is passed by
value. That is, a function always gets a copy of the thing being
passed, as if there were an assignment statement assigning the value
to the parameter. For instance, passing an int value to a function
makes a copy of the int, and passing a pointer value makes a copy of
the pointer, but not the data it points to.
Why does sort.Ints(arrayValue) modify the passed variable when I declared it as an array, not as a slice?
Code
var av = []int{1,5,2,3,7}
fmt.Println(av)
sort.Ints(av)
fmt.Println(av)
return
Output
[1 5 2 3 7]
[1 2 3 5 7]
See "Slices: usage and internals"
var av = []int{1,5,2,3,7}
That is a slice, not an array.
A slice literal is declared just like an array literal, except you leave out the element count.
That explains why the sort function will modify the content of what is referenced by the slice.
As commented below by Kirk, sort.Ints will give you an error if you passed it an array instead of a slice.
func Ints(a []int)
Because you're using a slice, not an array.
That is a slice:
var av = []int{1,5,2,3,7}
And those are arrays:
var av = [...]int{1,5,2,3,7}
var bv = [5]int{1,5,2,3,7}
If you try to compile:
var av = [...]int{1,5,2,3,7}
fmt.Println(av)
sort.Ints(av)
fmt.Println(av)
, you will get an error:
cannot use av (type [5]int) as type []int in function argument
as sort.Ints expects to receive a slice []int.
[]int{1,5,2,3,7} is not an array. An array has it's length in it's type, like [5]int{1,5,2,3,7}.
Make a copy of the slice and sort it instead:
a := []int{1,5,2,3,7}
sortedA := make([]int, len(a))
copy(sortedA, a)
sort.Ints(sortedA)
fmt.Println(a)
fmt.Println(sortedA)
slices are pointer to array . when you copy an array to another or when you pass a array in the function the entire copy of array is copied or passed . This makes a costlier operation if thae array size is large. so we can go for slices.
var av = []int{1,5,2,3,7}
in the above statement you are initializing slice like an array
To create an array the syntax should be
var av = [5]int{1,5,2,3,7}

Resources