I am getting an unusual result when attempting to place a value in an array.
I have an array table[] of a simple class result{ int score, long time, string ID}
Intention is to have a sort of leader board.
My code happily finds the correct place to insert a new score if it is in the top 10.
int ix = 0;
int jx = 10; //
while ( ix < jx )
{
if (points > sTable[ix].points)
{
// score is higher move records down
for (jx = mNumRecords - 1; jx >ix ; jx--)
{
sTable[jx] = sTable[jx -1];
}
//now add new score
sTable[ix].score = score; // all good until here
sTable[ix].time = time;
}
ix++;
}
Problem is that when I try to insert the score using sTable[ix].score = score;
The value gets written to sTable[ix].score and also sTable[ix +1].score.
It is repeatable, it occurs at any value of ix, I have single stepped through the code and as far as I can tell the command only executes once.
Has anyone seen this before?
That because you copied the object reference to the next element in the array. You should copy the values, or create a new object:
Option A:
// score is higher move records down
for (jx = mNumRecords - 1; jx >ix ; jx--)
{
sTable[jx].time = sTable[jx -1].time;
sTable[jx].score = sTable[jx -1].score;
}
//now add new score
sTable[ix].score = score; // all good until here
sTable[ix].time = time;
Option B:
for (jx = mNumRecords - 1; jx >ix ; jx--)
{
sTable[jx] = sTable[jx -1];
}
sTable[ix] = new Result(score, time, ""); // Or however you construct the object
Related
I am calling a function in a Class which will update a List Object. I have successfully get the desired object and change the values in it. How do I update back the original list?
Here is my code:
void updateTask(
Guid id, String title, String start, String end, String timeleft) {
final taskToBeUpdated = _tasks.firstWhere((element) => element.id == id);
taskToBeUpdated.title = title;
taskToBeUpdated.start = start;
taskToBeUpdated.end = end;
taskToBeUpdated.timeLeft = timeleft;
}
I know I can use the forloop to achieve this
for (var i = 0; i < _tasks.length; i++) {
if (_tasks[i].id == id) {
_tasks[i].title = title;
_tasks[i].start = start;
_tasks[i].end = end;
_tasks[i].timeLeft = timeleft;
}
}
But is there a shorter way?
Your first code should directly modify the object in the list since dart passes it by reference.
Try run this code to understand how this works:
List a = [{"dod":1}, {"dod":3}];
Map _b = a.firstWhere((e)=>e["dod"]==1);
_b["dod"] = 2;
print (a);
HI below is the code which gets the four columns data from the curson and put in the 2d array. basically there are two issues one is that i get the last value as nullnullnullnull means all for columns are fetched as null.
the seconds is that i want to print the array in multitextline or if any other widget availabe so that i get four fields in a row. like
id rule_body rule_con boole
0 abc def 1
0 a f 0
c.moveToFirst();
int i=0;
while(c.moveToNext()) {
String id = c.getString(c.getColumnIndex("id"));
String rb = c.getString(c.getColumnIndex("rule_body"));
String cn = c.getString(c.getColumnIndex("rule_cons"));
String bl = c.getString(c.getColumnIndex("boole"));
table[i][0] = id;
table[i][1] = rb;
table[i][2] = cn;
table[i][3] = bl;
++i;
}
for(int a=0;a<count_row;a++)
for(int b=0;b<count_col;b++) {
obj_ml.append(String.valueOf(table[a][b]));
}
so far i am getting all the result in a single line. any help will be appreciated.
Change your for-loop as below
for (int a=0;a<count_row;a++)
{
for(int b=0;b<count_col;b++)
{
obj_ml.append(String.valueOf(table[a][b]));
}
// add to obj_ml new line character '\n'
obj_ml.append("\n");
}
I want to get random data from database(sqlite) without repeat.Can anyone help me ..
DBManager *databaseManager = (DBManager *)[[DBManager alloc] init];
NSArray *array=[databaseManager readQuestionFromDatabase];
que=[array objectAtIndex:0];
self.lblQuestion.text=que.question;
[self.btnOption1 setTitle:que.questionoption1 forState:UIControlStateNormal];
[self.btnOption2 setTitle:que.questionoption2 forState:UIControlStateNormal];
[self.btnOption3 setTitle:que.questionoption3 forState:UIControlStateNormal];
[self.btnOption4 setTitle:que.questionoption4 forState:UIControlStateNormal];
This is another answer which uses same random number generation without repetition but avoids multiple query execution.
String randomRowData = "";
selQuery = "SELECT MYFIELD FROM MYTABLE ";
ArrayList<String> list = new ArrayList<Integer>(size);
for(int i = 1; i <= size; i++) {
list.add(MYFIELD_VALUE); // All DB Data here
}
Random rand = new Random();
while(list.size() > 0) {
int index = rand.nextInt(list.size());
randomRowData = list.remove(index); // Will display the rows without repetition
/* USE THE ROW DATA APPROPRIATELY */
}
This approach using Random Number Generation via java and ROWNUM for SQLITE should help you. But you might have to execute queries multiple times.
int DBSize = getDBSize();
int randomRowNum = 0;
ArrayList<Integer> list = new ArrayList<Integer>(size);
for(int i = 1; i <= size; i++) {
list.add(i);
}
Random rand = new Random();
while(list.size() > 0) {
int index = rand.nextInt(list.size());
randomRowNum = list.remove(index);
selQuery = "SELECT * FROM MYTABLE WHERE ROWNUM = " + randomRowNum + " ORDER BY SOME_UNIQUE_SORT_ORDER";
// EXECUTE SELECT QUERY AND YOU WOULD GET RANDOM ROWS here.
}
private int getDBSize ()
{
int retVal = 5;
retVal = // Select count(1) from myTable;
return retVal; //(Assuming I have 5 records in DB)
}
Note: Make sure your sort order in ORDER BY is unique. Else results would not be as expected.
My problem is I have around 1000+ records in an Android App
string field1;
string field2;
string field3;
string field4;
//...
I want to search in this set of records and get the best results on two fields (field1 and field2).
Currently I read each record and compare() (string compare) with the text i want to search so that takes a long time.
What is the best method to perform search?
Store each records in SQLite DB and do "select query where like"
Hash-Mapped
? any other suggestions?
Or may be create an Index of the records and do search.
If you want to search for not exact matches, I would try to make an ArrayList of MyAppRecord where
public class MyAppRecord {
private String record;
private int deviance;
}
and get for each record the deviance of the String you want to find with:
public static int getLevenshteinDistance (String s, String t) {
if (s == null || t == null) {
throw new IllegalArgumentException("Strings must not be null");
}
int n = s.length(); // length of s
int m = t.length(); // length of t
if (n == 0) {
return m;
} else if (m == 0) {
return n;
}
int p[] = new int[n+1]; //'previous' cost array, horizontally
int d[] = new int[n+1]; // cost array, horizontally
int _d[]; //placeholder to assist in swapping p and d
// indexes into strings s and t
int i; // iterates through s
int j; // iterates through t
char t_j; // jth character of t
int cost; // cost
for (i = 0; i<=n; i++) {
p[i] = i;
}
for (j = 1; j<=m; j++) {
t_j = t.charAt(j-1);
d[0] = j;
for (i=1; i<=n; i++) {
cost = s.charAt(i-1)==t_j ? 0 : 1;
// minimum of cell to the left+1, to the top+1, diagonally left and up +cost
d[i] = Math.min(Math.min(d[i-1]+1, p[i]+1), p[i-1]+cost);
}
// copy current distance counts to 'previous row' distance counts
_d = p;
p = d;
d = _d;
}
// our last action in the above loop was to switch d and p, so p now
// actually has the most recent cost counts
return p[n];
}
}
save it to your MyAppRecord-object and finally sort your ArrayList by the deviance of its MyAppRecord-objects.
Note that this could take some time, depending on your set of records. And NOTE that there is no way of telling wether dogA or dogB is on a certain position in your list by searching for dog.
Read up on the Levensthein distance to get a feeling on how it works. You may get the idea of sorting out strings that are possibly to long/short to get a distance that is okay for a threshold you may have.
It is also possible to copy "good enough" results to a different ArrayList.
I'm working on code that takes two arrays with strings (the strings are just sentences) and allocates them to classes which are held in another array (The Sentence class array shown below in the code).
So here's my problem. When popList() is called, the for loop runs through twice and works fine, putting the first index of addStrings and addTranslation into the first class in the array. However, when the loop indexes up and runs temp.sentence = addStrings[1] again, it OVERRIDES the first class's .sentence also. Then when temp.translations = addTranslations[1] runs again it OVERRIDES the first class's .translation.
So by the end of the loop, all of the arrays are filled with the same thing: the last index of addStrings and addTranslation. Every time it loops it overwrites all the indices before it with the index it's supposed to be putting in.
Anyone know what the problem is here? Thanks!
public class Sentence {
public String sentence;
public String translation;
Sentence() {
sentence = " ";
translation = " ";
}
}
private void popStrings() {
addStrings[0] = "我是你的朋友。"; addTranslations[0] = "I am your friend.";
addStrings[1] = "你可以帮助我吗?"; addTranslations[1] = "Could you help me?";
addStrings[2] = "我不想吃啊!"; addTranslations[2] = "I don't want to eat!";
}
//Fill Sentence array with string and translation arrays
private void popList() {
int i = 0;
Sentence temp = new Sentence();
for(i = 0; i < addStrings.length && i < addTranslations.length ; i++) {
temp.sentence = addStrings[i];
temp.translation = addTranslations[i];
sentences[i] = temp;
}
}
You need to create new Sentence() inside the loop:
for(i = 0; i < addStrings.length && i < addTranslations.length ; i++) {
Sentence temp = new Sentence();
temp.sentence = addStrings[i];
temp.translation = addTranslations[i];
sentences[i] = temp;
}
Otherwise you set sentence and translation continuously in the same object.