How do I periodically append to an array using the Arduino IDE? - arduino

I am trying to append float values that the user inputs through the serial monitor. I need these values stored in an array in a sequential fashion, i.e. each time I get a value, I must append it to the array.

Arduino doesn't come out of the box with dynamic data structures (except for String).
You can download open source implementations of generic containers from the web. Here's one: https://github.com/dhbikoff/Generic-C-Library/blob/master/vector.h
Also, here's a simple linked-list/vector I implemented myself as a toy project.
Be careful with dynamic memory. Memory fragmentation can cause your sketch to crash randomly (has happened to me several times).
template <typename T>
struct SimpleVector {
struct SimpleVectorNode {
T* m_value = NULL;
SimpleVectorNode* m_next = NULL;
SimpleVectorNode() {
}
SimpleVectorNode(T val) {
m_value = new T(val);
m_next = NULL;
}
};
int m_size = 0;
SimpleVectorNode* m_head = new SimpleVectorNode;
void AddValue(T val) {
++m_size;
SimpleVectorNode* end = m_head;
while (end->m_next != NULL) {
end = end->m_next;
}
end->m_next = new SimpleVectorNode(val);
}
SimpleVectorNode* Seek(int index) {
SimpleVectorNode* res = m_head;
while (index >= 0) {
--index;
res = res->m_next;
}
return res;
}
T& Get(int index) {
return *(Seek(index)->m_value);
}
void Delete(int index) {
SimpleVectorNode* preDel = Seek(index - 1);
SimpleVectorNode* toDel = preDel->m_next;
preDel->m_next = toDel->m_next;
delete toDel->m_value;
delete toDel;
--m_size;
}
int GetSize() {
return m_size;
}
int IndexOf(T val) {
SimpleVectorNode* pNode = m_head->m_next;
for (int i = 0; i < m_size; ++i) {
if (pNode->m_value == val) {
return i;
}
pNode = pNode->m_next;
}
return -1;
}
bool Contains(T val) {
return IndexOf(val) >= 0;
}
~SimpleVector() {
while (m_size > 0) {
Delete(0);
}
delete m_head;
}
};

Related

How to use prefix tree data structure

I have a smg file that contains different articles. Now I would like to use prefix tree data structure to establish baseline word counts for the entire corpus of documents. A sample of the file can be found below:
<REUTERS TOPICS="YES" LEWISSPLIT="TRAIN" CGISPLIT="TRAINING-SET"
OLDID="5544" NEWID="1">
<DATE>26-FEB-1987 15:01:01.79</DATE>
<TOPICS><D>cocoa</D></TOPICS>
<PLACES><D>el-salvador</D><D>usa</D><D>uruguay</D></PLACES>
<PEOPLE></PEOPLE>
<ORGS></ORGS>
<EXCHANGES></EXCHANGES>
<COMPANIES></COMPANIES>
<UNKNOWN>
C T
f0704reute
u f BC-BAHIA-COCOA-REVIEW 02-26 0105</UNKNOWN>
<TEXT>
<TITLE>BAHIA COCOA REVIEW</TITLE>
<DATELINE> SALVADOR, Feb 26 - </DATELINE><BODY>
Some text here.
Reuter
</BODY></TEXT>
</REUTERS>
Any advice on how to establish the baseline word counts?
use trie data structure to load strings and retrieve suggestions faster
public class Trie
{
public struct Letter
{
public const string Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static implicit operator Letter(char c)
{
c = c.ToString().ToUpper().ToCharArray().First();
return new Letter() { Index = Chars.IndexOf(c) };
}
public int Index;
public char ToChar()
{
return Chars[Index];
}
public override string ToString()
{
return Chars[Index].ToString();
}
}
public class Node
{
public string Word;
public bool IsTerminal { get { return Word != null; } }
public Dictionary<Letter, Node> Edges = new Dictionary<Letter, Node>();
}
public Node Root = new Node();
public Trie(string[] words)
{
for (int w = 0; w < words.Length; w++)
{
var word = words[w];
var node = Root;
for (int len = 1; len <= word.Length; len++)
{
var letter = word[len - 1];
Node next;
if (!node.Edges.TryGetValue(letter, out next))
{
next = new Node();
if (len == word.Length)
{
next.Word = word;
}
node.Edges.Add(letter, next);
}
node = next;
}
}
}
public List<string> GetSuggestions(string word, int max)
{
List<string> outPut = new List<string>();
var node = Root;
int i = 0;
foreach (var l in word)
{
Node cNode;
if (node.Edges.TryGetValue(l, out cNode))
{
node = cNode;
}
else
{
if (i == word.Length - 1)
return outPut;
}
i++;
}
GetChildWords(node, ref outPut, max);
return outPut;
}
public void GetChildWords(Node n, ref List<string> outWords, int Max)
{
if (n.IsTerminal && outWords.Count < Max)
outWords.Add(n.Word);
foreach (var item in n.Edges)
{
GetChildWords(item.Value, ref outWords, Max);
}
}
}

Recursive to Iterative method for Binary Search Tree

I'm working on an assignment to get the height of the BST using an iterative method from an recursive method. Below will be the provided recursive code and my code. It is returning one greater than the actual height. For example, the height is suppose to be 4, but it returns 5.
//Provided code
public int getHeight() {
return getHeight(root);
}
private int getHeight(Node node) {
if (node==null) {
return -1;
} else {
int leftHeight = getHeight(node.left);
int rightHeight = getHeight(node.right);
return Math.max(leftHeight, rightHeight) + 1;
}
}
//my code
public int getHeightI() {
return getHeightI(root);
}
private int getHeightI(Node node) {
Node curr = node;
int leftHeight = 0;
int rightHeight = 0;
if (curr!=null) {
while (curr.left!=null) {
leftHeight++;
curr = curr.left;
}
while (curr.right!=null) {
rightHeight++;
curr = curr.right;
}
}
return Math.max(leftHeight, rightHeight)+1;
}
Your Code is returning one more than actual height of Tree. I suggest you to use this code
int height(tree* root)
{
if(!root)
{ return -1;
}
else{
return __max(root->left,root->right);
}
Hope you understand your mistake.

Binary Search Tree implemented in Java - Find Element recursively

Using Java, is it possible to write a recursive method to find an element in a binary search tree? I say no because of the nature of recursive re-tracing back unless I implemented incorrectly? I have been searching the internet and all i can find is an iterative version. Here is my method:
public boolean findValueRecursively(BSTNode node, int value){
boolean isFound = false;
BSTNode currentNode = node;
if (value == currentNode.getData()){
isFound = true;
return isFound;
} else if (value < currentNode.getData()){
findValueRecursively(currentNode.getLeftNode(), value);
} else{
findValueRecursively(currentNode.getRightNode(), value);
}
return isFound;
}
// Node data structure
public class BSTNode
{
private BSTNode leftNode;
private BSTNode rightNode;
private int data;
public BSTNode(int value, BSTNode left, BSTNode right){
this.leftNode = left;
this.rightNode = right;
this.data = value;
}
}
public static void main(String[] args){
BST bst = new BST();
// initialize the root node
BSTNode bstNode = new BSTNode(4, null, null);
bst.insert(bstNode, 2);
bst.insert(bstNode, 5);
bst.insert(bstNode, 6);
bst.insert(bstNode, 1);
bst.insert(bstNode, 3);
bst.insert(bstNode, 7);
if (bst.findValueRecursively(bstNode, 7)){
System.out.println("element is found! ");
} else{
System.out.println("element is not found!");
}
}
I get the print as "element is not found".
Any help/tips or suggestions, more than welcome.
Thanks in advance!
A recursive version:
public boolean findValueRecursively(Node node, int value){
if(node == null) return false;
return
node.data == value ||
findValueRecursively(leftNode, value) ||
findValueRecursively(rightNode, value);
}
A recursive version that returns a reference to the node found:
public BinaryNode find(BinaryNode node, int value) {
// Finds the node that contains the value and returns a reference to the node.
// Returns null if value does not exist in the tree.
if (node == null) return null;
if (node.data == value) {
return node;
} else {
BinaryNode left = find(node.leftChild, value);
BinaryNode right = find(node.rightChild, value);
if (left != null) {
return left;
}else {
return right;
}
}
}
I believe your isFound = false; is what is always getting returned.
It should be like this:
isFound= findValueRecursively(currentNode.getLeftNode(), value);
public TreeNode<E> binarySearchTree(TreeNode<E> node, E data){
if(node != null) {
int side = node.getData().compareTo(data);
if(side == 0) return node;
else if(side < 0) return binarySearchTree(node.getRightChild(), data);
else if(side > 0 ) return binarySearchTree(node.getLeftChild(), data);
}
return null;
}
That will return a reference to the node, which is a little more useful IRL. You can change it to return a boolean though.

DevExpress GridControl Does not Update properly even I set up the NotifyPropertyChanged event correctly

I met a very strange Problem.
The basic idea is that I have a class to save data received from a trading api about forex price. Each property has been set with NotifyPropertyChanged method like below.
class RealTimeBar
{
public event PropertyChangedEventHandler PropertyChanged;
private const double EPSILON = 0.0000001;
private int _id;
private string _symbol;
private int _time;
private float _open;
private float _high;
private float _low;
private float _close;
int _volume;
public RealTimeBar(int id, string symbol)
{
_id = id;
_symbol = symbol;
}
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
public int Id
{
get
{
return _id;
}
set
{
_id = value;
}
}
public string Symbol
{
get
{
return _symbol;
}
set
{
if (value != _symbol)
{
_symbol = value;
NotifyPropertyChanged("Symbol");
}
}
}
public int Time
{
get
{
return _time;
}
set
{
if (value != _time)
{
_time = value;
NotifyPropertyChanged("Time");
}
}
}
public float Open
{
get
{
return _open;
}
set
{
if (value != _open)
{
_open = value;
NotifyPropertyChanged("Open");
}
}
}
public float High
{
get
{
return _high;
}
set
{
if (value != _high)
{
_high = value;
NotifyPropertyChanged("High");
}
}
}
public float Low
{
get
{
return _low;
}
set
{
if (value != _low)
{
_low = value;
NotifyPropertyChanged("Low");
}
}
}
public float Close
{
get
{
return _close;
}
set
{
if (value != _close)
{
_close = value;
NotifyPropertyChanged("Close");
}
}
}
public int Volume
{
get
{
return _volume;
}
set
{
if (value != _volume)
{
_volume = value;
NotifyPropertyChanged("Volume");
}
}
}
}
It is quote a long class but with simple structure as you can see. Now I connected to api which fire event to me and I handle it by set the value from api to the class i defined.
BindingList<RealTimeBar> _realTimeBarList = new BindingList<RealTimeBar>();
public Hashtable _iForexHashtable = new Hashtable();
private void _UpdateForexQuote(int tickerId, int time, double open, double high, double low, double close, int volume,
double wap, int count)
{
///MessageBox.Show(tickerId.ToString());
((RealTimeBar)_iForexHashtable[tickerId]).Open = (float)open;
((RealTimeBar)_iForexHashtable[tickerId]).High = (float)high;
((RealTimeBar)_iForexHashtable[tickerId]).Low = (float)low;
((RealTimeBar)_iForexHashtable[tickerId]).Close = (float)close;
((RealTimeBar)_iForexHashtable[tickerId]).Volume = volume;
}
After some setting up, the method _UpdateForexQuote would distribute the coming info into properties of RealTimeBar class. Everything is fine.
When I start the program, it does not update. I thought that there is no data coming in. But when I randomly click somewhere in the A1cell of gridcontrol, then click another B1cell, the previous A1cell would update. Then if i click C1cell, then the B1cell would update. If you do not click one cell , it would never update. I show you the picture:
As you can see, that after clicking first three lines, the first three lines showed delayed data and since I never touch the fourth line, it shows zero. And the condition is that I just clicked the fifth line Low cell, that is why the Low does not update but other cells updated. It is very strange. I use same code before under devexpress 11 with vs 2010. But now with devexpress 12 with vs 2012, I met this problem which never occurred before.
UPDATE:
Below is the method I use to 1. define bindinglist and a hashtable, 2. put objects into the hashtable first and add the object from hashtable to bindinglist 3. bind the bindinglist to gridcontrol.
private void earningButtonItem_ItemClick(object sender, ItemClickEventArgs e)
{
_iTimer.AutoReset = false;
_iTimer.Enabled = false;
switchStockPool = "Earning Stock";
disconnectButtonItem.PerformClick();
connectButtonItem.PerformClick();
_iheitanshaoEarningDBConnect = new DBConnect("heitanshaoearning");
List<string>[] tempList;
int tempHash;
tempList = _iheitanshaoEarningDBConnect.SelectSymbolHighLow();
_quoteEarningOnGridList.Clear();
///tempList[0].Count
for (int i = 0; i < tempList[0].Count; i++)
{
tempHash = Convert.ToInt32(tempList[0][i].ToString().GetHashCode());
_iStockEarningHistHashtable[tempHash] = new QuoteOnGridHist(tempList[0][i], (float)Convert.ToSingle(tempList[1][i]), (float)Convert.ToSingle(tempList[2][i]), (float)Convert.ToSingle(tempList[3][i]));
_iStockEarningHashtable[tempHash] = new QuoteOnGrid(tempList[0][i], 0, 0);
_quoteEarningOnGridList.Add((QuoteOnGrid)_iStockEarningHashtable[tempHash]);
reqMktDataExStock(tempHash, tempList[0][i].ToString());
}
List<string>[] tempVolumeList;
tempVolumeList = _iheitanshaoEarningDBConnect.SelectAverageVolume();
for (int i = 0; i < tempList[0].Count; i++)
{
tempHash = Convert.ToInt32(tempVolumeList[0][i].ToString().GetHashCode());
((QuoteOnGrid)_iStockEarningHashtable[tempHash]).Average_Volume = ((float)Convert.ToSingle(tempVolumeList[1][i])) / volumeDenominator;
}
gridControl.DataSource = _quoteEarningOnGridList;
}
/////////////////////
Now when the price update event comes, the method below will update the object properties in hashtable. Since I defined Notifypropertychanged in object, it should update the object in bingdinglist and gridcontrol.
private void _UpdateStockMarketQuote(int tikcerId, int field, double price, int canAutoExecute)
{
////MessageBox.Show(tikcerId.ToString() + field.ToString() + price.ToString());
if (switchStockPool == "Selected Stock")
{
if (field == 4)
{
((QuoteOnGrid)_iStockHashtable[tikcerId]).Gap_From_High = ((float)price - ((QuoteOnGridHist)_iStockHistHashtable[tikcerId]).High) / ((QuoteOnGridHist)_iStockHistHashtable[tikcerId]).Close;
((QuoteOnGrid)_iStockHashtable[tikcerId]).Gap_From_Low = ((float)price - ((QuoteOnGridHist)_iStockHistHashtable[tikcerId]).Low) / ((QuoteOnGridHist)_iStockHistHashtable[tikcerId]).Close;
((QuoteOnGrid)_iStockHashtable[tikcerId]).Last_Price = (float)price;
}
//else if (field == 1)
//{
// ((QuoteOnGrid)_iStockHashtable[tikcerId]).Gap_From_High = ((float)price - ((QuoteOnGridHist)_iStockHistHashtable[tikcerId]).High) / ((QuoteOnGridHist)_iStockHistHashtable[tikcerId]).Close;
// ((QuoteOnGrid)_iStockHashtable[tikcerId]).Gap_From_Low = ((float)price - ((QuoteOnGridHist)_iStockHistHashtable[tikcerId]).Low) / ((QuoteOnGridHist)_iStockHistHashtable[tikcerId]).Close;
//}
}
else if (switchStockPool == "Earning Stock")
{
if (field == 4)
{
((QuoteOnGrid)_iStockEarningHashtable[tikcerId]).Gap_From_High = ((float)price - ((QuoteOnGridHist)_iStockEarningHistHashtable[tikcerId]).High) / ((QuoteOnGridHist)_iStockEarningHistHashtable[tikcerId]).Close;
((QuoteOnGrid)_iStockEarningHashtable[tikcerId]).Gap_From_Low = ((float)price - ((QuoteOnGridHist)_iStockEarningHistHashtable[tikcerId]).Low) / ((QuoteOnGridHist)_iStockEarningHistHashtable[tikcerId]).Close;
((QuoteOnGrid)_iStockEarningHashtable[tikcerId]).Last_Price = (float)price;
}
//else if (field == 1)
//{
// ((quoteongrid)_istockearninghashtable[tikcerid]).gap_from_high = ((float)price - ((quoteongridhist)_istockearninghisthashtable[tikcerid]).high) / ((quoteongridhist)_istockearninghisthashtable[tikcerid]).close;
// ((quoteongrid)_istockearninghashtable[tikcerid]).gap_from_low = ((float)price - ((quoteongridhist)_istockearninghisthashtable[tikcerid]).low) / ((quoteongridhist)_istockearninghisthashtable[tikcerid]).close;
//}
}
}
Not only you need to have PropertyChanged event in a class, you need to implement INotifyPropertyChanged. That's how the grid knows a class can inform of changes.

It throws an stackoverflow exception when I user PropertyInfo.SetValue()

When I use PropertyInfo.SetValue in asp.net , it throws a stackoverflow exception.
That I write this code:
for (int i = 0; i < rivalSeriesIDList.Count; i++)
{
cardb_series rivalSeries = seriesBll.GetSeriesInfoByID(rivalSeriesIDList[i].ToString());
this.GetType().GetProperty("brandid" + (i + 1)).SetValue(this, rivalSeries.brand_id, null);
this.GetType().GetProperty("seriesid" + (i + 1)).SetValue(this, rivalSeries.series_id, null);
}
And brandid+number and seriesid+number is a property of aspx_page. like this:
public int brandid1
{
get
{
if (Request.Form["brandid1"] != null)
return int.Parse(Request.Form["brandid1"]);
if (Request["brandid1"] != null)
return int.Parse(Request["brandid1"]);
return 0;
}
set
{
brandid1 = value;
}
}
when I test the code in a Console Application ,It is all right . But when I test it in a Web Application ,it will cause a stack overflow exception .
I don't know why. Because of web is no-state?
Thanks.
cause you call your property recursively, and will get the same exception even if you will call the property directly
public int brandid1 <- this one
{
get
{
if (Request.Form["brandid1"] != null)
return int.Parse(Request.Form["brandid1"]);
if (Request["brandid1"] != null)
return int.Parse(Request["brandid1"]);
return 0;
}
set
{
and this one -> brandid1 = value;
}
}
I don't know what do you want to do, but try this
private int _brandid1;
public int brandid1 <- this one
{
get
{
if (Request.Form["brandid1"] != null)
return int.Parse(Request.Form["brandid1"]);
if (Request["brandid1"] != null)
return int.Parse(Request["brandid1"]);
return 0;
}
set
{
_brandid1 = value;
}
}

Resources