Returning Array Fragments - c#-3.0

I need to get array fragments from an array. I'm sick of using Array.Copy().
new ArraySegment(..).Array returns the original [full] array. The one below is what I came up with but I feel it's pretty lame. Is there a better way to do this?
class Program
{
static void Main(string[] args)
{
var arr = new ArraySegment<byte>(new byte[5] { 5, 4, 3, 2, 1 }, 0, 2).ArrayFragment();
for (int i = 0; i < arr.Length; i++)
Console.WriteLine(i);
Console.Read();
}
}
static class Extensions
{
public static T[] ArrayFragment<T>(this ArraySegment<T> segment)
{
var arr = new T[segment.Count];
Array.Copy(segment.Array, segment.Offset, arr, 0, segment.Count);
return arr;
}
}
Thanks in advance.
Update:
The above was just an example.
I have a method: byte [] CalculateXXX(byte [] key, byte [] message);
I do array manipulations inside this method. I want to return portion of an array.
ArraySegment does not implement IEnumerable and it does NOT return an array with just the segment new ArraySegment(arr...).Array returns the complete original array.
var rval = new byte[4];
//new ArraySegment(finalOutputBuffer, 0, 4).SegmentedArray();
Array.Copy(finalOutputBuffer, 0, rval, 0, 4);
I find I had to do the above to return a array fragment. Was just wondering if there's a better way of returning fragments of an array [as new array].

Vyas, I am truly sorry for having posted this useless pile of ****. It's been ages since I've actually used ArraySegment and I simply assumed that it implemented a (more or less) consistent interface. Someone (Jon?) please tell me which drugs were used during the implementation of this useless struct.
Finally, to make a long story short, the best solution is probably to implement your own version of ArraySegment, only doing it right.
I don't understand your problem with using ArraySegment. There's no additional overhead involved here, if that's what you mean, since no copying of the original data is done. Rather, ArraySegment offers a lightweight view on the data.
Th make this work, change your (return) type from T[] to IEnumerable<T>, or, if you need indexed access, to IList<T>. Generally prefer using interface types in method signatures, and completely avoid array types. The rationale is very simple: it makes problems such as yours go away and makes the interface more flexible and future-proof. It also provides better information hiding since it hides parts of the implementation which aren't relevant for the consumer of this method.

Define better. What is the downside with ArraySegment? What problem are you having that it doesn't solve?
Edit: Ok, I now understand your point of view, but this is wrong. It might be a bug in the sense that you feel it should do more, but it does exactly what it is supposed to do. It allows you to pass information to a piece of code about an array you wish to use, and which portion of the array to use.
It doesn't provide IEnumerable or anything that gives you a narrow view of the array, ie. x[0] doesn't give you the first element of the segment, nor can you foreach over it.
So yes, it's rather useless on its own, but you wouldn't be able to get something that is an array at heart, and yet is also a segment of a larger array.
You could easily make your own collection-like class that references an array and uses the array as storage, and provides indexing, enumeration, etc.
But that's not what this structure does. I guess the main problem here is that they made you expect more from it through its name.

Just another side-effect of poor iterator design in C# btw. There are many instances similar (just as 'lame') where it would just plain good design to be able to pass or point or control segments (aka concept called range) without all the archane shickanery.. copy semantics or not, array is also a well-defined concept.
Just use C++. :-)

Related

How to make copy of array's elements in the dart

Getting wired issue like main array has been changed if changed value of another array. I think issue is about copying same address, not sure but just thinking of it. I have tried from last 3 hours but unable to get rid from it.
Look at below illustration to get better idea.
List<page> _pageList;
List<page> _orderList = [];
_pageList = _apiResponse.result as List<page>;
_orderList.add(_pageList[0].element);
_orderList[0].title = "XYZ"
//--> Here if I change the `_orderList[0].title` then it also change the `title` inside "_pageList"
How can we prevent the changes in main array?
I got same issue in my one of the project. What I have done is, use json to encode and decode object that help you to make copy of the object so that will not be affected to the main List.
After 3rd line of your code, make changes like below
Elements copyObject = Elements.fromJson(_pageList[0].element.toJson());
// First of all you have to convert your object to the Map and and map to original object like above
_orderList.add(copyObject);
Hope that will help you.
You can use a getter function to create a copy of your list and use that instead of
altering your actual list.
example:
List<Page> get orderList{
return [..._orderList];
}
Lists in Dart store references for complex types, so this is intended behaviour.
From your code:
_orderList.add(_pageList[0].element);
_orderList[0] and _pageList[0].element point to the same reference (if they are non-primitive).
There is no general copy() or clone() method in dart, as far as i know. So you need to copy the object yourself, if you want a separate instance. (see this question)

Make long names shorter in Unity?

Instead of writing a code like
FindObjectOfType<GameManager>().gameOver()
I would like to type just
gm.gameOver()
Is there a way to do that in Unity?
Maybe using some kind of alias, or some kind of namespace or something else. I am after making my code clean, so using GameManger gm = FindObjectOfType() in every file that uses a the GameManager is not what I am looking for.
In general I have to discourage this question. This is very questionable and I would actually not recommend this kind of shortening aliases for types and especially not for a complete method call ... bad enough when it is done with variables and fields by a lot of people.
Always use proper variable and field names thus that by reading the code you already know what you are dealing with!
how about storing it in a variable (or class field) at the beginning or whenever needed (but as early as possible)
// You could also reference it already in the Inspector
// and skip the FindObjectOfType call entirely
[SerializeField] private _GameManager gm;
private void Awake()
{
if(!gm) gm = FindObjectOfType<_GameManager>();
}
and then later use
gm.gameOver();
where needed.
In general you should do this only once because FindObjectOfType is a very performance intense call.
This has to be done of course for each class wanting to use the _GameManager instance ...
However this would mostly be the preferred way to go.
Alternatively you could also (ab)use a Singleton pattern ... it is controversial and a lot of people hate it kind of ... but actually in the end FindObjectOfType on the design side does kind of the same thing and is even worse in performance ...
public class _GameManager : MonoBehaviour
{
// Backing field where the instance reference will actually be stored
private static _GameManager instance;
// A public read-only property for either returning the existing reference
// finding it in the scene
// or creating one if not existing at all
public static _GameManager Instance
{
get
{
// if the reference exists already simply return it
if(instance) return instance;
// otherwise find it in the scene
instance = FindObjectOfType<_GameManager>();
// if found return it now
if(instance) return instance;
// otherwise a lazy creation of the object if not existing in scene
instance = new GameObject("_GameManager").AddComponent<_GameManager>();
return instance;
}
}
private void Awake()
{
instance = this;
}
}
so you can at least reduce it to
_GameManager.Instance.gameOver();
the only alias you can create now would be using a using statement at the top of the file like e.g.
using gm = _GameManager;
then you can use
gm.Instance.gameOver();
it probably won't get much shorter then this.
But as said this is very questionable and doesn't bring any real benefit, it only makes your code worse to read/maintain! What if later in time you also have a GridManager and a GroupMaster? Then calling something gm is only confusing ;)
Btw you shouldn't start types with a _ .. rather call it e.g. MyGameManager or use a different namespace if you wanted to avoid name conflicts with an existing type

Guava : Is Cache.asMap().remove() better?

I want to get & remove an item from Cache
final Cache<String, PendingRequest> pendingRequest = CacheBuilder.newBuilder().build();
// get first
pendingCall = pendingRequest.getIfPresent(key);
pendingRequest.invalidate(key); // then remove.
I also found another way
pendingCall = pendingRequest.asMap().remove(key);
Does asMap method clone all the items? Is it a heavy call? Which manner is better if considering performance.
There's no real difference between those calls because Cache#asMap() is defined as:
Returns a view of the entries stored in this cache as a thread-safe map. Modifications made to the map directly affect the cache.
Calling asMap() may be slightly less performant (because it's possible a view has to be created) but the time is constant (and negligible) and is an implementation detail (see internal Guava LocalCache and LocalManualCache classes for more details).
What's more important, Cache#invalidate(K) is more idiomatic and I'd recommend using it instead of map view methods (edit after #BenManes' comment below) if you don't need returned value associated with the key, otherwise use map view.

Lua light userdata

I have a problem with Lua and I don't know if I going in the right direction. In C++ I have a dictionary that I use to pass parameter to a resource manager. This dictionary is really similar to a map of hash and string.
In Lua I want to access to these resource so I need a representation of hashes. Also hashes must be unique cause are used as index in a table. Our hash function is 64bit and I'm working on 32bit enviroment (PS3).
C++ I have somethings like that:
paramMap.insert(std::make_pair(hash64("vehicleId"), std::string("004")));
resourceManager.createResource(ResourceType("Car"), paramMap);
In Lua want use these resources to create a factory for other userdata.
I do stuff like:
function findBike(carId)
bikeParam = { vehicleId = carId }
return ResourceManager.findResource('car', bikeParam)
end
So, sometime parameter are created by Lua, sometime parameter are created by C++.
Cause my hashkey ('vehicleId') is an index of a table it need to be unique.
I have used lightuserdata to implement uint64_t, but cause I'm in a 32bit enviroment I can't simply store int64 in pointer. :(
I have to create a table to store all int64 used by the program and save a reference in userdata.
void pushUInt64(lua_State *L, GEM::GUInt64 v)
{
Int64Ref::Handle handle = Int64Ref::getInstance().allocateSlot(v);
lua_pushlightuserdata(L, reinterpret_cast<void*>(handle));
luaL_setmetatable(L, s_UInt64LuaName);
}
but userdata are never garbage collected. Then my int64 are never released and my table will grow forever.
Also lightuserdata don't keep reference to metadata so they interfere with other light userdata. Checking the implementation the metadata table is added in L->G_->mt_[2].
doing that
a = createLightUserDataType1()
b = createLightUserDataType2()
a:someFunction()
will use the metatable of b.
I thought that metatable where bounded to type.
I'm pretty confused, with the current implementation lightuserdata have a really limited use case.
With Python you have a hash metafunction that is called anytime the type is used as index for a dictionary. It's possible to do something similar?
Sorry for my english, I'm from Italy. :-/

Is inheritance the right choice for this 'story and option' based adventure application?

A friend and myself are creating a Goosebumps-style adventure game, where at each stage the user is presented with a potential set of 4 choices, and the user's choice affects the outcome of the story.
What data structure should I use for this?
This is my main idea -- Objects
In trying to keep the game as close to the real life idea of these cards as possible, create one 'card' base class, and have lots of other cards inherit from this - superclass would contain Stringx5( x1story x4choiceStories) intx5 (x1CardIDNumber x4CardIDChoices).
This would then allow me to pump out objects easily with the material we already have, and have a system class controlling all the processing for user choices and displaying information onscreen. And again with the system in place and a base card class, it would allow for different stories in the future and whatnot. Trying to make this as reusable as possible and write as little code as possible (I'm not writing over a thousand if Statements.)
One thing that isn't clear to me (and the actual reason I'm posting this question in my inability to find the answer): isn't inheritance meant to be for other classes that are similar but with slight differences, e.g. managers and employees, making my idea completely wrong and a massive waste of memory?
I have looked into the following:
Hash tables: the examples seem to be more phone book oriented, and I don't think it would suit my needs
Abstraction to define a story type: also doesn't seem to suit my needs
No real need for inheritance as the cards are exactly the same, just the data on them changes. I'd use inheritance if there were special cards that need to behave differently to all the rest.
You can do what you want with something like this pseudo code:
class Card {
Card getChoice(int i); // returns choices[i]
string storyText;
Card[] choices; // Use an stl collection rather than an array for ease of addition.
}
Basically you create each card so it links to all the other cards (trick here is making sure you create the cards in the right order - easy solution: create them with no choices and add the different choices via an addChoice(Card) method later.
Your Game class starts with the first card (basically the head of a tree to all the cards), and does something like:
Card runCard(Card card)
{
Card nextCard = null;
showStoryText(card);
// Display a line for each choice in the card and get the user's response.
// Convert the response to the correct index.
int selection = promptForAction(card);
if (selection >= 0 && selection < card.numChoices()) {
nextCard = card.getChoice(selection);
}
return nextCard;
}
void run()
{
Card card = firstCard;
while(card != null) {
card = runCard(card);
}
}
This shouldn't be too bad. Essentially you need a tree structure.
Your main class could look like (forgive my lack of knowledge of c++)
class Node {
Node option1;
Node option2;
Node option3;
Node option4;
}
So your Node instances can point to other instances of Node.
It's probably better to have some sort of collection of Node instances, that way you can have as many or as few as you want. You can add a field to Node that indicates which option it is (1, 2, etc).
The only other thing you need is reference to the initial Node.