How to navigate in an Array of strings left and right - arrays

I have an array of strings
var characters = ["Jim", "Anna", "Nick", "Chris", "Peter"];
my initial position is Jim[0]. if i type right i want to go to the next one
In this case to "Anna". I can do this by adding one to the current index.
The thing is getting more tricky when i type left from the initial position?
So how can i go from Jim[0] -> Peter[4]?
Something that works is
Jim[0] - 1 + characters.length which equals to 0 - 1 + 5 = 4
and this is Peter. But this seems incorrect because i cannot do that in the case that the current value is Anna[1] and i want to go to Jim[0]. As 1 - 1 + 5 = 5

Something like this would work.
var characters = ["Jim", "Anna", "Nick", "Chris", "Peter"];
var index = 0; // Currently at Jim.
var direction = -1; // 1 for right, -1 for left.
// What's left of our current position?
characters[(index + characters.length + direction) % characters.length]; // Peter!

You could do a conditional. Keep your index in a variable instead of hard-coding it. This will allow you to do something similar to the pseudocode following (Sorry, wasn't sure which language this was for):
new_index = index--
if (new_index < characters.length)
index = characters.length - 1
You can then use that determined index to access the array. You could something similar to wrap around going forwards as well.

There seems to be no single formula to calculate the left and right index without using conditions.
If you don't intend to use if-else or just want a single line solution, you can use the ternary operator as follows:
new_index = (direction=="left")?(index==0)?characters.length-1:index-1:(index==characters.length-1)?0:index+1
Please note that the above code assumes there are only 2 possible directions.

This is what you're looking for
(i % characters.length) + characters.length) % characters.length
var characters = ["Jim", "Anna", "Nick", "Chris", "Peter"];
var index;
for( var i = -10; i < 10; i++ ){
index = ((i % characters.length) + characters.length) % characters.length;
console.log(i + " > " + index + " = " + characters[index]);
}

Related

Removing rows from matrix

I have a question above removing rows from a matrix. I have the code below which removes the rows I want, but the problem is each time a row is removed it changes the size of the matrix. When the size of the matrix changes, the for loops can no longer run through the original size of the matrix because it has changed. Does anyone know how to get around this? Thanks.
for i = 1:NT
for j = 1:NP
for k = 1:NP
if ContactPartData((i-1)*(NP*(NP-1)) + ((j-1)*NP + k),2) == 0
ContactPartData((i-1)*(NP*(NP-1)) + ((j-1)*NP + k),:) = [];
else
end
end
end
end
For these cases, it is typically easier to record which rows you want to remove, and then remove them all at once at the end. This is more efficient than repeatedly removing a single row. And it solves your problem at the same time!
toremove = false(size(ContactPartData,1),1);
for i = 1:NT
for j = 1:NP
for k = 1:NP
if ContactPartData((i-1)*(NP*(NP-1)) + ((j-1)*NP + k),2) == 0
toremove((i-1)*(NP*(NP-1)) + ((j-1)*NP + k)) = true;
end
end
end
end
ContactPartData(toremove,:) = [];
Of course, in this particular case, the loop is not needed at all:
toremove = ContactPartData(:,2) == 0;
ContactPartData(toremove,:) = [];
Additionally, it might be more efficient to do it the other way around, selecting which rows to preserve (time the code to find out!):
tokeep = ContactPartData(:,2) ~= 0;
ContactPartData = ContactPartData(tokeep,:);

Trouble understanding one line in Insertion Sort (Python 3)

I was looking through the other threads concerning the Insertion Sort but didn't find the answer that relates to the specific part of it which I do not understand.
My full Insertion Sort algorithm can be seen below. It works as intended, but I cannot figure out the purpose of that last line.
array[position] = value
Let me explain through an example:
When the 'for' loop starts, index = 1.
=> value = array[1] = 3
=> position = 1
=> Since 4 > 3, the item at index 1, is swapped with the item at index 0.
=> position -= 1
=> position = 0
We now get to the line which confuses me:
array[0] = value
=> value = array[index] = array[0] = 3
However, when the 'for' loop goes through its second iteration, index = 2.
And so immediately value = array[2] and position = 2 ?
Even though I know that this last line of code is necessary I just cannot see what purpose it serves.
Could someone please explain to me this final logical step?
Thank you in advance for your time and help.
array = [4,3,5,6,12,9,8,6]
for index in range (1, len(array)):
value = array[index]
position = index
while position > 0 and array[position - 1] > value:
array[position] = array[position - 1]
position -= 1
array[position] = value
The position variable represents (at the end) where you will eventually insert the number. Without the last line, you are not inserting the number at 'position' at the correct place (it will result in the 1 index after). Below is my code for insertion sort.
def insertionSort(arr):
length = len(arr)
for i in range(1, length):
currNum = arr[i]
j = i - 1
while j >= 0 and currNum < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j+1] = currNum
return arr
You wouldn't have really swapped the numbers without that line, would you?
index 1:
-> [4,3,5,6,12,9,8,6] (enters while loop)
-> [4,4,5,6,12,9,8,6] ("pushes" 4 to position 1)
-> <waits for while loop to finish>
-> [3,4,5,6,12,9,8,6] (assigns 3 to position 0 since there are no other elements > 3)
index 2:
...
I think is not really needed at start in for loop, because it was used to index inside the loop. Looks the picture

adjacentElementsProduct function in ruby

I'm stuck on an algorithm for a function called adjacentElementsProduct that accepts an array as the argument. It's supposed to return the largest product of adjacent numbers in the array. For example, if the argument is [2,4,1,3,2,6] it would return 12 because of the pair of 2 and 6.
my code is
def adjacentElementsProduct(inputArray)
idx1 = 0
idx2 = 1
while idx2 < inputArray.length
pair = [inputArray[idx1], inputArray[idx1 + 1]]
next_pair = [inputArray[idx2], inputArray[idx2 + 1]]
if next_pair.reduce(:+) > pair.reduce(:+)
pair = next_pair
idx1 += 1
idx2 += 1
else
idx1 += 1
idx2 += 1
end
end
pair.reduce(:+)
end
I just can't figure out where my code is not working. I'm just looking for a push in the right direction because I know just being given the answer won't help me as much. Can anyone help me?
The code makes no sense :).
You are using + instead of *
And in the loop you always assign pair = [inputArray[idx1], inputArray[idx1 + 1]].
So you always return the last pair or the previous. If the maximum product is at the beginning, you still keep advancing the pair variable until the end of the loop.
Besides, the solution is quite complicated.
def adjacentElementsProduct(inputArray)
index = 0
length = inputArray.length
max = 0
while index < length-1 do
result = inputArray[index] * inputArray[index+1]
max = result if result > max
index += 1
end
max
end

MATLAB: search for elements in an array matching multidimensional condition

I have a column vector (V1) of real numbers like:
123.2100
125.1290
...
954.2190
If I add, let's say, a number 1 to each row in this vector, I will get (V2):
124.2100
126.1290
...
955.2190
I need to find out how many elements from V2 are inside some error-window created from V1. For example the error-window = 0.1 (but in my case every element in V1 has it's own error window):
123.1100 123.3100
125.0290 125.2290
...
954.1190 954.3190
I can create some code like this:
% x - my vector
% ppm - a variable responsible for error-window
window = [(1-(ppm/1000000))*x, (1+(ppm/1000000))*x]; % - error-window
mdiff = 1:0.001:20; % the numbers I will iteratively add to x
% (like the number 1 in the example)
cdiff = zeros(length(mdiff),1); % a vector that will contain counts of elements
% corresponding to different mdiff temp = 0;
for i = 1:length(mdiff)
for j = 1:size(window,1)
xx = x + mdiff(i);
indxx = find( xx => window(j,1) & xx <= window(j,2) );
if any(indxx)
temp = temp + length(indxx); %edited
end
end
cdiff(i) = temp;
temp = 0;
end
So, at the end cdiff will contain all the counts corresponding to mdiff. The only thing, I would like to make the code faster. Or is there a way to avoid using the second loop (with j)? I mean to directly use a multidimensional condition.
EDIT
I decided to simpify the code like this (thanking to the feedback I got here):
% x - my vector
% ppm - a variable responsible for error-window
window = [(1-(ppm/1000000))*x, (1+(ppm/1000000))*x]; % - error-window
mdiff = 1:0.001:20; % the numbers I will iteratively add to x
% (like the number 1 in the example)
cdiff = zeros(length(mdiff),1); % a vector that will contain counts of elements
% corresponding to different mdiff temp = 0;
for i = 1:length(mdiff)
xx = x + mdiff(i);
cdiff(i) = sum(sum(bsxfun(#and,bsxfun(#ge,xx,window(:,1)'),bsxfun(#le,xx,window(:,2)'))));
end
In this case the code works faster and seems properly
add = 1; %// how much to add
error = .1; %// maximum allowed error
V2 = V1 + add; %// build V2
ind = sum(abs(bsxfun(#minus, V1(:).', V2(:)))<error)>1; %'// index of elements
%// of V1 satisfying the maximum error condition. ">1" is used to because each
%// element is at least equal to itself
count = nnz(ind);
Think this might work for you -
%%// Input data
V1 = 52+rand(4,1)
V2 = V1+1;
t= 0.1;
low_bd = any(abs(bsxfun(#minus,V2,[V1-t]'))<t,2); %%//'
up_bd = any(abs(bsxfun(#minus,V2,[V1+t]'))<t,2); %%//'
count = nnz( low_bd | up_bd )
One could also write it as -
diff_map = abs(bsxfun(#minus,[V1-t V1+t],permute(V2,[3 2 1])));
count = nnz(any(any(diff_map<t,2),1))
Edit 1:
low_bd = any(abs(bsxfun(#minus,V2,window(:,1)'))<t,2); %%//'
up_bd = any(abs(bsxfun(#minus,V2,window(:,2)'))<t,2); %%//'
count = nnz( low_bd | up_bd )
Edit 2: Vectorized form for the edited code
t1 = bsxfun(#plus,x,mdiff);
d1 = bsxfun(#ge,t1,permute(window(:,1),[3 2 1]));
d2 = bsxfun(#le,t1,permute(window(:,2),[3 2 1]));
t2 = d1.*d2;
cdiff_vect = max(sum(t2,3),[],1)';

MATLAB: Finding the entry number of the first '1' in a logical array

I have created a logical array of 1's and 0's using the following code:
nWindow = 10;
LowerTotInitial = std(LowerTot(1:nWindow));
UpperTotInitial = std(UpperTot(1:nWindow));
flag = 0;
flagArray = zeros(length(LowerTot), 1);
for n = 1 : nData0 - nWindow
for k = 0 : nWindow - 1
if LowerTot(n + k) < 0.1*LowerTotInitial || UpperTot(n + k) < 0.1*UpperTotInitial
flag = 1;
flagArray(n) = 1;
else
flag = 0;
end
end
end
This returns flagArray, an array of 0's and 1's. I am trying to find the index of the first 1 in the array. ie. 1 = flagArray(index). I am confused as to what is the best way to accomplish this!
What you call an entry number is referred to as an index in MATLAB-speak. To find the index of the first matching element in an array you can use the FIND function:
>> x = [0 0 1 0 1 0];
>> find(x, 1, 'first')
ans =
3
Try this ind = find(flagArray, k, 'first')
with k =1
Read this Matlab Docs - find

Resources