Making a Copy of an Array Independent of the Original - arrays

var ary:Array = ["string","string","string"];
var copy_ary:Array = ary;
trace(copy_ary);//string,string,string
ary[1]=false;
trace(copy_ary);//string,false,string
All I want to do is make a copy of the array ary without the copy constantly changing in accordance with the original. Would I have to create a copy with a loop (e.g. below)?
var ary:Array = ["string","string","string"];
var copy_ary:Array = [];
for(var i=0;i<ary.length;i++){
copy_ary[i]=ary[i];
}
Obviously this works, but it seems a lot of work considering one wouldn't think the copied array would constantly stay the same as the original in the first place. Could someone please tell me why this is?

In your first example you didn't create a new array - you created a new reference to an already existing array (so you had 2 references but 1 array). When you modify the array through one reference, you'll see changes through the other reference as well (since you really only have 1 array).
To create an independent copy of an array, you need to actually create a new array instance and then copy the items over. This can be done through a shallow or through a deep copy.
In short, a shallow copy can be created using the Array.concat() or the Array.slice() methods (or using a loop, like in your 2nd example). For a deep copy, you'll have to also copy the objects inside the array - this would likely need more code, depending on what kind of objects are in the array.
When your array only contains primitive (or pimitive-like) types, a shallow copy is typically enough - if your array only has strings, a shallow copy should be enough since String behaves like a primitve type even though it's a complex object.
Read this article for more information.

Related

Why does `append(x[:0:0], x...)` copy a slice into a new backing array in Go?

On Go's slice tricks wiki and Go libraries (e.g., this example), you sometimes see code like the following to copy a slice into a new backing array.
// In a library at the end of a function perhaps...
return append(whateverSlice[:0:0], whateverSlice...)
// In an assignment, as in the wiki example...
b = append(a[:0:0], a...)
Here's what I think I understand:
All of the items in the slice that is the second parameter to append are copied over to a new backing array.
In the first parameter to append, the code uses a full slice expression. (We can rewrite the first parameter as a[0:0:0], but the first 0 will be supplied if omitted. I assume that's not relevant to the larger meaning here.)
Based on the spec, the resulting slice should have the same type as the original, and it should have a length and capacity of zero.
(Again, not directly relevant, but I know that you can use copy instead of append, and it's a lot clearer to read.)
However, I still can't fully understand why the syntax append(someSlice[:0:0], someSlice...) creates a new backing array. I was also initially confused why the append operation didn't mess with (or truncate) the original slice.
Now for my guesses:
I'm assuming that all of this is necessary and useful because if you just assign newSlice := oldSlice, then changes to the one will be reflected in the other. Often, you won't want that.
Because we don't assign the result of the append to the original slice (as is normal in Go), nothing happens to the original slice. It isn't truncated or changed in any way.
Because the length and capacity of anySlice[:0:0] are both zero, Go must create a new backing array if it's going to assign the elements of anySlice to the result. Is this why a new backing array is created?
What would happen if anySlice... had no elements? A snippet on the Go Playground suggests that if you use this append trick on an empty slice, the copy and the original initially have the same backing array. (Edit: as a commenter explains, I misunderstood this snippet. The snippet shows that the two items are initially the same, but neither has a backing array yet. They both point initially to a generic zero value.) Since the two slices both have a length and capacity of zero, the minute you add anything to one of them, that one gets a new backing array. Therefore, I guess, the effect is still the same. Namely, the two slices cannot affect each other after the copy is made by append.
This other playground snippet suggests that if a slice has more than zero elements, the append copy method leads immediately to a new backing array. In this case, the two resulting slices come apart, so to speak, immediately.
I am probably worrying way too much about this, but I'd love a fuller explanation of why the append(a[:0:0], a...) trick works the way it does.
Because the length and capacity of anySlice[:0:0] are both zero, Go must create a new backing array if it's going to assign the elements of anySlice to the result. Is this why a new backing array is created?
Because capacity is 0, yes.
https://pkg.go.dev/builtin#go1.19.3#append
If it has sufficient capacity, the destination is resliced to accommodate the new elements. If it does not, a new underlying array will be allocated.
cap=0 is NOT sufficient for non-empty slice, allocating a new array is necessary.

Difference between Dynamic arrays and list c#

I have a query regarding a concept.
Are dynamic arrays in c# also called list? Or they are totally different?
C# does not have a dynamic array type. However, you can use a List as a dynamic array, given that it supports indexed access:
List<string> list = new List<string>();
list.Add("Hello");
list.Add("Goodbye");
Console.WriteLine(list[1]);
Take a look at Generic Lists.
Since it's the first link I found out when looking for this difference I would like to contribute a little.
The Nitin Bisht response is not entirely wrong, but by most of programming definitions a dynamic array is a type of array that can be set when the program is already running, simply put, it's size is set during run time not in compilation.
In C# this is written as:
string[] myDynamicArray;
myDynamicArray = SomeMethodThatReturnsAnCollection().ToArray();
Other way would be a method which returns an existing array like:
string[] myDynamicArray;
myDynamicArray = SomeMethodThatReturnsAnArray();
Those are Dynamic Arrays, you don't tell your program which size it has but inside the logic of that context this will be decided.
Those Arrays in C# has the Resize method, which enables the programmer to grow the array, which I believe it was the Nitin Bisht and so many others interpretation around that question, but this is a wrong assumption, resizable is different than dynamic.
Instead of using Resize in your Array, you could just use a List type, List in C# implements an Array in it's core, which can be seen here, but it also has the ability to grow in an easier approach than the Array implementation enables us with the Add(T item) List method.
List in C# would be a native Dynamic Resizable Array, some languages call similarly implementations of this structure as Vector, which are not a LinkedList with nodes and pointers for example.
Summarizing the difference in code:
var myList = new List<string> { "initial value" };
myList.Add("New value"); // After add, myList has this new value
var myArray = new string[] { "initial value" };
myArray.Append("New value") // after Append myArray doesnt have a new value
With Append() method what happens is another IEnumerable collection is created with the new value, so if you iterate through both collections you will see that the list prints out the new value but the array doesn't, in that case one way you can fix that is doing this:
string[] myArray;
myArray = myArray.Append("New value").ToArray(); // now it will work
The difference here is that myArray variable is being rewritten with the new array generated by .Append().ToArray() line, in the List example the Add() method will resize and then add the new value.
Important to note that this resize is done in a similar manner than what we did with the Append() "fixed" code, the List creates a new Array with increased size and copies it's original contents to this new Array.
You can use the resources given by the Array class to get to the same result as the Add() method implemented by List, but off course if you need that method you should just use an List instead of writing your own implementation, very rarely you would have to do it and to be honest your implementation would be probably less efficient than the already built ones.
In summary that is the difference between them, as you can see they have similarities but I would still treat them very differently.
Usually you wanna use an array when you do not expect to grow any further, if that is your case then an array is more useful since it's has less implementations and that brings a performance gain which can be good in a lot of scenarios.
If not, just use lists.

Updating string array using java stream

I know that for object, we can forEach the collection and update the object as we like but for immutable objects like Strings, how can we update the array with new object without converting it into an array again.
For e.g, I have an array of string. I want to iterate through each string and trim them. I would otherwise have to do something like this:
Arrays.stream(str).map(c -> c.trim()).collect(Collectors.toList())
In the end, I will get a List rather then String[] that I initially gave. Its a whole lot of processing. Is there any way I can do something similar to:
for(int i = 0; i < str.length; i++) {
str[i] = str[i].trim();
}
using java streams?
Streams are not intended for manipulating other data structures, especially not for updating their source. But the Java API consists of more than the Stream API.
As Alexis C. has shown in a comment, you could use Arrays.setAll(arr, i -> arr[i].trim());
There’s even a parallelSetAll that you could use when you have a really large array.
However, it might be easier to use just Arrays.asList(arr).replaceAll(String::trim);.
Keep in mind that the wrapper returned by Arrays.asList allows modifications of the wrapped array through the List interface. Only adding and removing is not supported.
Use toArray :
str = Arrays.stream(str).map(c -> c.trim()).toArray(String[]::new);
The disadvantage here (over your original Java 7 loop) is that a new array is created to store the result.
To update the original array, you can re-write your loop with Streams, though I'm not sure what's the point :
IntStream.range (0, str.length).forEach (i -> {str[i] = str[i].trim();});
It's not that much processing as you might think, the array has a known size and the spliterator from it will be SIZED, thus the resulting collection size will be known before processing and the space for it can be allocated ahead of time, without having to re-size the collection.
It's also always interesting that in the absence of actual tests we almost always assume that this is slow or memory hungry.
of course if you want an array as the result there is a method for that :
.toArray(String[]::new);

In order to preallocate memory in Matlab, I want to initialize my array of objects. How do I do this?

I have a class of objects known as blocks. Currently, I am creating an array of blocks using a for loop by simply tacking them unto an empty array
blockArray=[];
for ii=1:Size
blockArray=[blockArray block(....)];
end
In order to preallocate memory, how do I initialize an object array of blocks with dummy values?
For instance if instead of using block objects I used numbers, I could easily preallocate by using zeros(1,Size). Is there something similar that I could do?
The matlab documentation describes
To preallocate the object array, assign the last element of the array first. MATLAB® fills the first to penultimate array elements with default DocArrayExample objects.
So, to do this, instead of iterating over from 1:size, it is simpler to do...
blockArray = []
blockArray(size) = block(...)
The language does not really support this, there exists multiple solutions (or workarounds).
Replicating the first instance
When pushing the first element into the array, you can fill the whole array with this element to achieve a preallocation. This might look very bad, but it is actually the fastest possibility known to me.
for ii=1:S
%assumption e is a scalar, otherwise the code is totally screwed
e=block(....)
if ii==1
%to do preallocation, fill it with your first element
blockArray(1:S)=e
else
blockArray(ii)=e
end
end
Use cell arrays
Obvious simple solution, you can put any class into the fields
blockArray=cell(S,1);
for ii=1:S
%assumption e is a scalar, otherwise the code is totally screwed
e=block(....)
blockArray{ii}=e
end
This solution is very simple but slower than the first. You also lose some functionality which is not available for cell arras
Let your class implement array functionality
classdef A
properties
arg1
out
end
methods
function obj = A(varargin)
if nargin==0
%null object constructor
elseif strcmpi(varargin{1},'createarray')
sz=varargin(2:end);
%preallocate
obj(sz{:})=A;
else
%standard constructor
obj.arg1=varargin{1};
obj.out=[1 2 3;];
end
end
end
end
Constructor with no input argument creates an "empty" or "null" object, this is used to preallocate so it should be empty.
Constructor with first parameter makearray creates an array
Otherwise your constructor should be called.
Usage:
%create an empty object
A
%create an array of size 2,3,4
A('createarray',2,3,4)
%use the standard constructor
A(2)
Biggest downside is you have to modify your classes. Never tested this solution, but it should be close to the first in performance.

matlab initialize array of objects

I am playing around with OOP in MATLAB, and I have the following constructor:
function obj = Squadron(num_fighters, num_targets, time_steps)
if nargin == 0
num_targets = 100;
time_steps = 100;
num_fighters = 10;
end
obj.num_shooters = num_fighters;
for iShooter = 1:obj.num_shooters
a(iShooter) = Shooter(num_targets, time_steps);
end
obj.ShooterArray = a;
obj.current_detections = zeros(num_fighters, num_targets);
end
That temporary variable 'a' smells terrible. Is there a better way to initialize an array of objects, I wish there was a push/pop method. I am sure there is a better way to do this.
Looks like you are trying to create an array of handle objects (Shooters) and store it inside the property of another handle object (a Squardron). I have had a very similar problem discussion that might help you.
In short: What you are doing might not be pretty - but might be pretty good already.
When creating an array in Matlab it is usually a good Idea to do some pre-allocation to reserve memory which speeds up performance significantly.
In a normal case something like this:
a=zeros(1,1000);
for n=1:1000
a(n)=n;
end
(here a=1:1000; would be even better)
For objects the pre-allocation works by assigning one of the objects to the very last field in the array. Matlab then fills the other fields before that with objects (handles) that it creates by calling the constructor of that object with no arguments (see Matlab help). Hence a pre-allocation for objects could look like this:
a(1,1000)=ObjectConstructor();
for n=1:1000
a(n)=ObjectConstructor();
end
or simply
for n=1000:-1:1
a(n)=ObjectConstructor();
end
Making sure Shooter can be called with no arguments you should be able to do something like:
for iShooter = obj.num_shooters:-1:1
obj.ShooterArray(iShooter) = Shooter(num_targets, time_steps);
end
However, it turns out that for some reason this direct storing of an array of objects in another object's property creates very bad performance. (Probably the array pre-allocation does not work well in this case). Hence using an auxiliary variable and allocating the full array at once to the property is in this case is a good idea to increase performance.
I would try:
for iShooter = obj.num_shooters:-1:1
a(iShooter) = Shooter(num_targets, time_steps);
end
obj.ShooterArray = a;
Again - for more detail see this discussion
There are a couple of ways to handle this situation...
Building object arrays in the constructor:
You could modify your Shooter class such that when you pass arrays of values it creates an array of objects. Then you could initialize ShooterArray like so:
obj.ShooterArray = Shooter(repmat(num_targets,1,num_fighters),...
repmat(time_steps,1,num_fighters));
Replicating instances of a value class:
If Shooter is a value class, and each object is going to be exactly the same (i.e. you don't initialize any of its default properties to random values), then you can create just one object and replicate it using REPMAT:
obj.ShooterArray = repmat(Shooter(num_targets,time_steps),1,num_fighters);
Unfortunately, if Shooter is a subclass of the handle class, you can't just replicate it as you can with a value class. You would actually be replicating references to just one object, when you really need a number of separate objects each with their own unique reference. In such a case, your current code is likely the best solution.

Resources