determine if array contains specific integer in octave - arrays

I have an array which looks like
test = {1,2,3};
I want to determine if an integer belongs in the array. I tried using ismember() and any() but they both return this:
binary operator '==' not implemented for 'cell' by 'scalar' operations
How will I do this? Thanks in advance

If you want to check if an integer exists in a matrix:
test = [1, 2, 3];
any (test == 2)
ans = 1
But in your question you use a cell array. In this case I would first convert it to a matrix, then do the same:
b = {1,2,3};
any (cell2mat (b) == 2)
ans = 1

You're asking about checking if an array has a given integer but you're using a cell. They're quite different.
If you want to stick to cells you can iterate over it like so
test = {1, 2, 3};
number = 2;
hasNumber = false;
for i = 1:size(test,2)
if(test{i} == number)
hasNumber = true;
break;
end
end
For arrays, on the other hand, you could do just this, for example
test = [1, 2, 3];
number = 2;
hasNumber = ~isempty(test(test == number));

Related

Setting up Arrays in one line

Im trying to set up an array with six integer values and one string in one line. I know how to do this one line at a time but cant figure out how to set it up in GameMaker.
array[0] = 10;
array[1] = 1;
array[2] = 5;
array[3] = 12;
array[4] = 12;
array[5] = 3;
array[6] = spr_sprite;
But ideally id like to avoid having multiple lines of code if i can. So how do i set it up in one line?
You can use that extention from the Marketplace (script array_create). Or create it yourself:
/// array_create(value1, value2, ...)
var res;
var n = argument_count - 1;
while (n-- >= 0)
{
res[n] = argument[n];
}
return res;
Old verisons of GMS may use 16 arguments maximum, but some time ago this limit was removed and now you can use about 700 arguments (actually I don't remember exact value and I guess this may differ on different hardware).
On GMS2 you can initialize arrays using the syntax
var a = [1, 2, 3, 4];

Creating an array with characters and incrementing numbers

Pretty simple problem, I want to create an array with char in a for loop.
code:
a = [1:5];
arr = [];
for i = 1:length(a)
arr(i) = ['f_',num2str(i)]
end
I am getting error:
In an assignment A(I) = B, the number of elements in B and I must be the same.
all i want is an array:
[f_1 f_2 f_3....]
This is because arr(i) is a single element, while ['f:', num2str(i)] contain three characters. Also, for i = 1:length(1) doesn't really make sense, since length(1) is guaranteed to be 1. I guess you wanted for i = 1:length(a). If that's the case I suggest you substitute length with numel and i with ii.
The better way to create the array you want is using sprintf like this:
sprintf('f_%i\n',1:5)
ans =
f_1
f_2
f_3
f_4
f_5
Or possiblby:
sprintf('f_%i ',1:5)
ans =
f_1 f_2 f_3 f_4 f_5
I guess this is what you really wanted:
for ii = 1:5
arr{ii} = ['f_', num2str(ii)];
end
arr =
'f_1' 'f_2' 'f_3' 'f_4' 'f_5'
Or simpler:
arr = arrayfun(#(n) sprintf('f_%i', n), 1:5, 'UniformOutput', false)
The last two can be indexed as follows:
arr{1}
ans =
f_1
You can also do (same result):
str = sprintf('f_%i\n', 1:5);
arr = strsplit(str(1:end-1), '\n')
If you're doing this to create variable names, then please don't. Use cells or structs instead.

How do I deal with specific elements only in an array?

So I know how to add up all the elements of an array using a for loop. But how would I go about adding up only the positive elements?
Say my array included {3, -9, 2, -10}
I want to: 3 + 2 (giving 5)
NOT: 3 +-9 +2 +-10 (giving -14)
Also how would I get the amount of positive elements in an array? (i.e. in this example there are two positive elements)
Im using Java/Eclipse
Thanks so much for the answers - i now know what to do! This is my first time here - do i have to mark this as answered or something?
You can just add a condition in your loop :
arrays = {3, -9, 2, -10};
sum = 0;
nb_elem = 0;
for (i = 0 ; i < arrays.length ; i++)
{
if (arrays[i] > 0)
{
sum += arrays[i];
nb_elem++;
}
}
I don't know what language you are using, so I'll give you example in Python
def sum_up_positive_values(array):
result = 0
for value in array:
if value > 0:
result += value
return result

Find if one integer array is a permutation of other

Given two integer arrays of size N, design an algorithm to determine whether one is a permutation of the other. That is, do they contain exactly the same entries but, possibly, in a different order.
I can think of two ways:
Sort them and compare : O(N.log N + N)
Check if the array have same number of integers and the sum of these integers is same, then XOR both the arrays and see if the result is 0. This is O(N). I am not sure if this method will eliminate false positives completely. Thoughts. Better algorithms?
Check if the array have same number of integers and the sum of these integers is same, then XOR both the arrays and see if the result is 0.
This doesn't work. Example:
a = [1,6] length(a) = 2, sum(a) = 7, xor(a) = 7
b = [3,4] length(b) = 2, sum(b) = 7, xor(b) = 7
Others have already suggested HashMap for an O(n) solution.
Here's an O(n) solution in C# using a Dictionary<T, int>:
bool IsPermutation<T>(IList<T> values1, IList<T> values2)
{
if (values1.Count != values2.Count)
{
return false;
}
Dictionary<T, int> counts = new Dictionary<T, int>();
foreach (T t in values1)
{
int count;
counts.TryGetValue(t, out count);
counts[t] = count + 1;
}
foreach (T t in values2)
{
int count;
if (!counts.TryGetValue(t, out count) || count == 0)
{
return false;
}
counts[t] = count - 1;
}
return true;
}
In Python you could use the Counter class:
>>> a = [1, 4, 9, 4, 6]
>>> b = [4, 6, 1, 4, 9]
>>> c = [4, 1, 9, 1, 6]
>>> d = [1, 4, 6, 9, 4]
>>> from collections import Counter
>>> Counter(a) == Counter(b)
True
>>> Counter(c) == Counter(d)
False
The best solution is probably a counting one using a map whose keys are the values in your two arrays.
Go through one array creating/incrementing the appropriate map location and go through the other one creating/decrementing the appropriate map location.
If the resulting map consists entirely of zeros, your arrays are equal.
This is O(N), and I don't think you can do better.
I suspect this is approximately what Mark Byers was going for in his answer.
If a space complexity of O(n) is not a problem, you can do it in O(n), by first storing in a hash map the number of occurrences for each value in the first array, and then running a second pass on the second array and check that every element exists in the map, decrementing the number the occurrences for each element.
Sort the contents of both arrays numerically, and then compare each nth item.
You could also take each item in array1, and then check if it is present in array2. Keep a count of how many matches you find. At the end, the number of matches should equal the length of the arrays.

Vectors and dynamic arrays in D

I was thinking that dynamic arrays were a replacement for vectors in D, but it seems they have no remove function (only associative arrays do) which is rather a limitation for a vector so I'm wondering if I've got that right. If a have an array like follows,
uint[] a;
a.length = 3;
a[0] = 1;
a[1] = 2;
a[2] = 3;
Then the only way I've found to remove, say, the second element is,
a = a[0..1] ~ a[2];
But that doesn't seem right (but maybe only because I don't understand this all yet). So is there a vector and is there another way of removing an element from a dynamic array?
Thanks.
You could use std.algorithm.remove(), which works not only with arrays but with generic ranges. Example:
import std.algorithm;
void main() {
uint[] a = [1, 2, 3];
a = a.remove(1);
assert(a == [1, 3]);
}
In std.container there is an Array!T template, which appears to be much like std::vector from C++.
Array!int a = [0, 1, 2, 3];
a.linearRemove(a[1..3]);
assert(equal(a, [0, 3]));
Unfortunately it does not appear to have an individual remove method, although you could always use linearRemove with a singleton range.

Resources