I'm trying to write a code that searches a list and matches a term. In this case 'bus' what I am then trying to do is to get the values for distance and time for that method and add them to separate lists. Attached is my code
distanceb = [];
timeb = [];
for i =1:n
if strcmp(method(i),'bus') == 1
distanceb = (x(i))
timeb = time(i)
end
end
I can get the values for the x and time but the code seems to overwrite everytime it adds to the list and I get only one answer for distanceb and timeb. Is there a way to add the values to the list without overwriting the previous value?
You are assigning new values to distanceb and timeb as scalars and not as lists/vectors.
You need to append values:
distanceb(end+1) = x(i);
timeb(end+1) = time(i);
A few remarks:
If you know the final size of distanceb and timeb it is best to pre-allocate them and not grow them inside the loop.
It is best not to use i as a variable name in Matlab.
Related
I am storing a collection of objects in a SplayTreeSet
class Obj {
final DateTime date;
Obj(this.date);
}
var list = [Obj(DateTime(2020)), Obj(DateTime(2021)]; //can contain many elements
listInOrder = SplayTreeSet.from(list.values, (a, b) => b.date.compareTo(a.date));
I would like to perform slices to listInOrder to get elements between certain dates. The range of dates is small compared to the length of objects.
Of course I could do that by looping and skipping / taking elements:
List<ArchivedBattle> getObjsBetween(DateTime from, DateTime to) {
return listInOrder.skipWhile((e) => e.date.isAfter(to)).takeWhile((e) => e.date.isAfter(from)).toList();
}
I wonder if I could do better and use the fact that the list is in order to find the start of the region that I want to get.
SplayTreeSet itself does not look like it is providing the functionality that I am looking for.
There is binarySearch function takes a List, so I would need make a copy of the data which is not a good option.
How could I get a slice of an ordered set in log(n) + k time? (k being the number of objects in the range)
This function is supposed to go through all of the list items and check whether the argument coordinates are close to the position in the list items (the second and third numbers in the nested lists), but from the readout I can tell that it only ever checks the first one.
function CapitalProximity(x,y)
local positions = {{"lusitani",31,328},{"ebdani",78,592},{"carpetani",101,329}}
for i = 1, #positions do
local dist = distance_2D(x,y,positions[i][2],positions[i][3])
print("position is "..dist.." from "..positions[i][1])
if dist < 20 then
return true
else
return false
end
end
end
Since both branches of the if return from inside the loop, the loop can never reach a second iteration. To get results based on all elements from the positions array, you need to make a table to store them:
function CapitalProximity(x,y)
local positions = {{"lusitani",31,328},{"ebdani",78,592},{"carpetani",101,329}}
local result = {} -- This will hold all results.
for i = 1, #positions do
local dist = distance_2D(x,y,positions[i][2],positions[i][3])
print("position is "..dist.." from "..positions[i][1])
result[i] = dist < 20 -- Store the current result.
end
return result
end
My function definition looks like
nxt_comb[] = Combination(comb[1:k],n)
This function should give the next combination which comes after the input combination comb (array). The n elements of comb takes values from 1 to n.
Example:
if function is called as a = Combination([1,3,4,6],8), then a = [1,3,4,7]
if function is called as a = Combination([1,3,4,8],8), then a = [1,3,5,6]
if function is called as a = Combination([1,3,7,8],8), then a = [1,4,5,6]
if function is called as a = Combination([3,6,7,8],8), then a = [4,5,6,7]
The input combination will never be the last combination. That is, in the above case the input will be never [5,6,7,8].
Also, if the input is all zeros, the function must output the first combination that is [1,2,....,k].
Edit: What I am looking for is the logic. The implementation can be in either C/C++ or MATLAB.
Leaving aside the last requirement about starting with all 0's, which is a trivial extra check, the algorithm is:
By searching backwards, find the largest i such that comb[i]<i+n-k (using 1-based indexing; adjust if you're using C). If you can't find one, you're at the last combination.
Increment comb[i], and then working from j = i+1 up to k, set comb[j] to comb[j-i]+1
I'm in my first semester of studies and as a part of my comp. science assignment I have to implement a simple hash map using vectors, but I have some problems understanding the concept.
First of all I have to implement a hash function. To avoid collisions I thought it would be better to use double hashing, as follows:
do {
h = (k % m + j*(1+(k % (m-2)));
j++;
} while ( j % m != 0 );
where h is the hash to be returned, k is the key and m is the size of hash_map (and a prime number; they are all of type int).
This was easy, but then I need to be able to insert or remove a pair of key and the corresponding value in the map.
The signature of the two functions should be bool, so I have to return either true or flase, and I'm guessing that I should return true when there is no element at position h in the vector. (But I have no idea why remove should be bool as well).
My problem is what to do when the insert function returns false (i.e. when there is already a key-value pair saved on position h - I implemented this as a function named find). I could obviously move it to the next free place by simply increasing j, but then the hash calculated by my hash function wouldn't tell us anymore at which place a certain key is saved, causing wrong behaviour of remove function.
Is there any good example online, that doesn't use the pre defined STD methods? (My Google behaves wierdly in the past few days and only reutrns me unuseful hits in the local language)
I've been told to move my comment to an answer so here it is. I am presuming your get method takes the value you are looking for an argument.
so what we are going to do is a process called linear probing.
when we insert the value we hash it as normal lets say our hash value is 4
[x,x,x,,,x,x]
as we can see we can simply insert it in:
[x,x,x,x,,x,x]
however if 4 is taken when we insert it we will simply move to the next slot that is empty
[x,x,x,**x**,x,,x,x]
In linear probing if we reach the end we loop back round to the beginning until we find a slot. You shouldn't run out of space as you are using a vector which can allocate extra space when it starts getting near full capacity
this will cause problems when you are searching because the value at 4 may not be at 4 anymore (in this case its at 5). To solve this we do a little bit of a hack. Note that we still get O(1) run time complexity for inserting and retrieval as long as the load balance is below 1.
in our get method instead of returning the value in the array at 4 we are instead going to start looking for our value at 4 if its there we can return it. If not we look at the value at 5 and so on till we find the value.
in psudo code the new stuff looks like this
bool insert(value){
h = hash(value);
while(node[h] != null){
h++;
if( h = node.length){
h = 0;
}
}
node[h] = value;
return true;
}
get
get(value){
h = hash(value);
roundTrip = 0; //used to see if we keep going round the hashmap
while(true){
if(node[h] == value)
return node[h];
h++;
if( h = node.length){
h = 0;
roundTrip++;
}
if(roundTrip > 1){ //we can't find it after going round list once
return -1;
}
}
}
I am working on a binary linear program problem.
I am not really familiar with any computer language(just learned Java and C++ for a few months), but I may have to use computer anyway since the problem is quite complicated.
The first step is to declare variables m_ij for every entry in (at least 8 X 8) a matrix M.
Then I assign corresponding values of each element of a matrix to each of these variables.
The next is to generate other sets of variables, x_ij1, x_ij2, x_ij3, x_ij4, and x_ij5, whenever the value of m_ij is not 0.
The value of x_ijk variable is either 0 or 1, and I do not have to assign values for x_ijk variables.
Probably the simplest way to do it is to declare and assign a value to each variable, e.g.
int* m_11 = 5, int* m_12 = 2, int* m_13 = 0, ... int* m_1n = 1
int* m_21 = 3, int* m_12 = 1, int* m_13 = 2, ... int* m_2n = 3
and then pick variables, the value of which is not 0, and declare x_ij1 ~ x_ij5 accordingly.
But this might be too much work, especially since I am going to consider many different matrices for this problem.
Is there any way to do this automatically?
I know a little bit of Java and C++, and I am considering using lp_solve package in C++(to solve binary integer linear program problem), but I am willing to use any other language or program if I could do this easily.
I am sure there must be some way to do this(probably using loops, I guess?), and this is a very simple task, but I just don't know about it because I do not have much programming language.
One of my cohort wrote a program for generating a random matrix satisfying some condition we need, so if I could use that matrix as my input, it might be ideal, but just any way to do this would be okay as of now.
Say, if there is a way to do it with MS excel, like putting matrix entries to the cells in an excel file, and import it to C++ and automatically generate variables and assign values to them, then this would simplify the task by a great deal!
Matlab indeed seems very suitable for the task. Though the example offered by #Dr_Sam will indeed create the matrices on the fly, I would recommend you to initialize them before you assign the values. This way your code still ends up with the right variable if something with the same name already existed in the workspace and also your variable will always have the expected size.
Assuming you want to define a square 8x8 matrix:
m = zeros(8)
Now in general, if you want to initialize a three dimensional matrixh of size imax,jmax,kmax:
imax = 8;
jmax = 8;
kmax = 5;
x = zeros(imax,jmax,kmax);
Now assigning to or reading from these matrices is very easy, note that length and with of m have been chosen the same as the first dimensions of x:
m(3,4) = 4; %Assign a value
myvalue = m(3,4) %read the value
m(:,1) = 1:8 *Assign the values 1 through 8 to the first column
x(2,4,5) = 12; %Assign a single value to the three dimensional matrix
x(:,:,2) = m+1; Assign the entire matrix plus one to one of the planes in x.
In C++ you could use a std::vector of vectors, like
std::vector<std::vector<int>> matrix;
You don't need to use separate variables for the matrix values, why would you when you have the matrix?
I don't understand the reason you need to get all values where you evaluate true or false. Instead just put directly into a std::vector the coordinates where your condition evaluates to true:
std::vector<std::pair<int, int> true_values;
for (int i = 0; i < matrix.size(); i++)
{
for (int j = 0; j < matrix[i].size(); j++)
{
if (some_condition_for_this_matrix_value(matrix[i][j], i, j) == true)
true_values.emplace_back(std::make_pair(i, j));
}
}
Now you have a vector of all matrix coordinates where your condition is true.
If you really want to have both true and false values, you could use a std::unordered_map with a std::pair containing the matrix coordinates as key and bool as value:
// Create a type alias, as this type will be used multiple times
typedef std::map<std::pair<int, int>, bool> bool_map_type;
bool_map_type bool_map;
Insert into this map all values from the matrix, with the coordinates of the matrix as the key, and the map value as true or false depending on whatever condition you have.
To get a list of all entries from the bool_map you can remove any false entries with std::remove_if:
std::remove_if(bool_map.begin(), bool_map.end(),
[](const bool_map_type::value_type& value) {
return value.second == false;
};
Now you have a map containing only entries with their value as true. Iterate over this map to get the coordinates to the matrix
Of course, I may totally have misunderstood your problem, in which case you of course are free to disregard this answer. :)
I know both C++ and Matlab (not Python) and in your case, I would really go for Matlab because it's way easier to use when you start programming (but don't forget to come back to C++ when you will find the limitations to Matlab).
In Matlab, you can define matrices very easily: just type the name of the matrix and the index you want to set:
m(1,1) = 1
m(2,2) = 1
gives you a 2x2 identity matrix (indices start with 1 in Matlab and entries are 0 by default). You can also define 3d matrices the same way:
x(1,2,3) = 2
For the import from Excel, it is possible if you save your excel file in CSV format, you can use the function dlmread to read it in Matlab. You could also try later to implement your algorithm directly in Matlab.
Finally, if you want to solve your binary integer programm, there is already a built-in function in Matlab, called bintprog which can solve it for you.
Hope it helps!