How do I create a multidimensional array of objects in c# - c#-4.0

I am trying to make a script that dynamically generates world chunks by making a height map then filling out the terrain blocks from there. My problem is creating a 2 dimensional array of objects.
public class Chunk
{
public Block[,] blocks;
Generate(){
//code that makes a height map as a 2 dimensional array as hightmap[x,y]=z
//convert heightmap to blocks
for (int hmX = 0; hmX < size; hmX++)
{
for (int hmY = 0; hmY < size; hmY++)
{
blocks[hmX, hmY] = new Block(hmX, hmY, heightmap.Heights[hmX, hmY], 1);
}
}
}
}
this is giving me the error:
NullReferenceException was unhandled, Object reference not set to an
instance of an object.

You just need to add new before the loop:
Block[,] blocks = new Block[size,size];
Or rather, within the generate function (all else the same):
blocks = new Block[size,size];
Otherwise you'll be shadowing the original 'blocks' variable.

Related

Subset Leetcode, size of a List

I am really curios about one thing when compiling, in the given code below, where I am creating nested for loop, I am giving as a limit
subsetArr.size()
but when compiling it is saying memory exceeded, and if I define size just before the for loop
int size = subsetArr.size()
and then passing limit as size
i<size;
it is working fine. What can be the cause?
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> subsetArr = new ArrayList<>();
subsetArr.add(new ArrayList());
for(int num: nums){
for(int i=0; i<subsetArr.size(); i++){
List<Integer> takenList = new ArrayList<>(subsetArr.get(i));
takenList.add(num);
subsetArr.add(takenList);
}
}
return subsetArr;
}
}
Look at what this loop does:
for(int i=0; i<subsetArr.size(); i++){
List<Integer> takenList = new ArrayList<>(subsetArr.get(i));
takenList.add(num);
subsetArr.add(takenList); // <-- here
}
Each iteration adds to the collection. So in the next iteration, subsetArr.size() will be larger. Thus you have a loop which indefinitely increases the size of the collection until it runs out of resources.
Contrast that to when you store the value:
int size = subsetArr.size();
In this case, while subsetArr.size() may change, size won't unless you update it. So as long as you don't update size then you have a finite loop.

C++\Cli Parallel::For with thread local variable - Error: too many arguments

Trying to implement my first Parallel::For loop with a tread local variable to sum results of the loop. My code is based on an example listed in "Visual C++ 2010, by W. Saumweber, D. Louis (German). Ch. 33, P.804).
I get stuck in the implementation with syntax errors in the Parallel::For call. The errors are as follows, from left to right: a) expected a type specifier, b) too many arguments for generic class "System::Func", c) pointer to member is not valid for a managed class, d) no operator "&" matches these operands.
In line with the book, I create a collection with data List<DataStructure^> numbers, which is subject to a calculation performed in method computeSumScore which is called by the Parallel::For routine in method sumScore. All results are summed in method finalizeSumScore using a lock.
Below I paste the full code of the .cpp part of the class, to show what I have. The data collection "numbers" may look a bit messy, but that's due to organical growth of the program and me learning as I go along.
// constructor
DataCollection::DataCollection(Form1^ f1) // takes parameter of type Form1 to give acces to variables on Form1
{
this->f1 = f1;
}
// initialize data set for parallel processing
void DataCollection::initNumbers(int cIdx)
{
DataStructure^ number;
numbers = gcnew List<DataStructure^>();
for (int i = 0; i < f1->myGenome->nGenes; i++)
{
number = gcnew DataStructure();
number->concentrationTF = f1->myOrgan->cellPtr[cIdx]->concTFA[i];
number->stringA->AddRange(f1->myGenome->cStruct[i]->gString->GetRange(0, f1->myGenome->cChars));
number->stringB->AddRange(f1->myGenome->cStruct[i]->pString);
if (f1->myGenome->cStruct[i]->inhibitFunc)
number->sign = -1;
else
number->sign = 1;
numbers->Add(number);
}
}
// parallel-for summation of scores
double DataCollection::sumScore()
{
Parallel::For<double>(0, numbers->Count, gcnew Func<double>(this, &GenomeV2::DataCollection::initSumScore),
gcnew Func<int, ParallelLoopState^, double, double>(this, &GenomeV2::DataCollection::computeSumScore),
gcnew Action<double>(this, &GenomeV2::DataCollection::finalizeSumScore));
return summation;
}
// returns start value
double DataCollection::initSumScore()
{
return 0.0;
}
// perform sequence alignment calculation
double DataCollection::computeSumScore(int k, ParallelLoopState^ status, double tempVal)
{
int nwScore;
if (numbers[k]->concentrationTF > 0)
{
nwScore = NeedlemanWunsch::computeGlobalSequenceAlignment(numbers[k]->stringA, numbers[k]->stringB);
tempVal = Mapping::getLinIntMapValue(nwScore); // mapped value (0-1)
tempVal = (double) numbers[k]->sign * tempVal * numbers[k]->concentrationTF;
}
else
tempVal = 0.0;
return tempVal;
}
// locked addition
void DataCollection::finalizeSumScore(double tempVal)
{
Object^ myLock = gcnew Object();
try
{
Monitor::Enter(myLock);
summation += tempVal;
}
finally
{
Monitor::Exit(myLock);
}
}
Once this problem is solved I need to ensure that the functions called (computeGlobalSequenceAlignment and getLinIntMapvalue) are thread safe and the program doesn't get stalled on multiple treads accessing the same (static) variables. But this needs to work first.
Hope you can help me out.
Hans Passant answered my question in the comments (include full method name, add comma). Yet I cannot mark my question as answered, so this answer is to close the question.

can we perform binary search on linked lists?

there was a reputed site which claimed that we cannot do binary search on linked list but I know for a fact that we can perform merge sort( which uses divide and conquer just like binary search) on a linked list so we must be able to perform binary search on a linked list as well right??
Purely in the abstract, a linked list does not support direct indexing. The only way to get to the third element is by starting at the first element, following the next link to the second element, then following it's next link to the third element.
If the implementation allows for indexing (e.g., java.util.LinkedList), it is possible to implement a binary search by calling get(index) when you need an element. If the underlying data structure is a simple linked list without an auxiliary lookup structure, then this will perform very poorly. As an example, the following is the code from the OpenJDK java.util.LinkedList.get method.
package java.util;
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{
transient int size = 0;
transient Node<E> first;
transient Node<E> last;
public E get(int index) {
return node(index).item;
}
Node<E> node(int index) {
if (index < (size >> 2)) {
Node<E> x = first;
for (int i = 0; i < index; i++)
x = x.next;
return x;
} else {
Node<E> x = last;
for (int i = size - 1; i > index; i--)
x = x.prev;
return x;
}
}
}
When list.get(5) is called to get the sixth element in a list of more than 11 elements, it iterates over the first five elements before returning the sixth. The generic interface provides indexed access into the sequence but makes no guarantees on its performance.

How to set the selection items for CComboBox to be the CString array all at once?

I am look for the combobox to display 4 rows where the first row shows "a", 2nd row shows "b"..."c"..."d"
cb1 = new CComboBox;
cb1->Create( WS_VSCROLL | CBS_DROPDOWN | WS_VISIBLE | WS_BORDER, CRect(20,200,200, 300), this, 30 );
CString itemSet[] = {"a","b","c","d"};
//I am to set the array all at once with out doing each itme ??
cb1.AddString(itemSet); //fails
There's no function to do so in one go. You could do as Jeeva suggest, a simple loop traversing your array:
CString itemSet[] = {"a","b","c","d"};
for (int i = 0; i < _countof(itemSet); ++i)
{
cb1.AddString(itemSet[i]);
}
However, if you are going to use it often, you could create your own CCombobox derived class and add a function that does it.
class CMyCombo : public CCombobox
{
public:
CMyCombo();
void AddStrings(const CString* strings, int num);
// ...
}
void CMyCombo::AddStrings(const CString* strings, int num)
{
for (int i = 0; i < num; ++i)
{
cb1.AddString(strings[i]);
}
}
Actually, I would probably use a container, such as std::vector or CStringArray, but you get the idea.
By the way, if you are using strings that could be localized, you should not rely on strings only. A better approach can be found here.
One last thing: there's usually no need to create controls on the fly. It's usually easier to create member variables for them.
Do something like this
CString arr[2] = {_T("A"),_T("B")};
for(int i =0 ;i <2; i++)
{
m_ctrlCombo.AddString(arr[i]);
}

Java ME ArrayList - Vector - Define object types and access object methods through vector

I'm making a shopping list mobile application (Java ME) and i have two classes; item, list.
item object allows get/set name and quantity (string itemName, int quantity)
Now i need to store an array of items in my list class and be able to access the methods of the object from its list array index as follows; code below is pseudo code
item[] itemList = new item[]
for(int x = 0; x < itemList.length; x++)
{
String tempStoreOfName = itemList[x].getItemName()
System.out.println(tempStoreOfName)
}
I've googled a lot and found out that you can use vectors however i cannot seem to be able to call the object's methods. Where am i going wrong?
I've done something like this in C# and i used ArrayLists however these are not supported in Java ME
Current Code
Vector itemList = new Vector();
for(int x = 0; x <= itemList.size(); x++)
{
dataOutputStream.writeUTF(itemList.elementAt(x)*here i cannot put .getItemName()*);
}
Since you can't use generics you have to cast so that Java knows what you got out of the Vector. Notice that Vector.elementAt() returns Object? all you can do with it is treat it like an Object:
item myItem = itemList.elementAt(n);
fails because java can't auto-cast to a more specific class. You'd have to use:
Object myItem = itemList.elementAt(n);
which is useless to you because you want an item, not an Object.
You have to cast it to an object of the type you want:
for(...)
{
item myItem = (item) itemList.elementAt(n);
myItem.method();
}
From then on you just use myItem.

Resources