How Can I Creat Method do This Job? - arrays

I want create method that return an array which contains exactly the same numbers as the given array, but rearranged so that every 3 is immediately followed by a 4.
Do not move the 3's, but every other number may move. The array contains the same number of 3's and 4's, every 3 has a number after it that is not a 3 or 4, and a 3 appears in the array before any 4.
Example:
problem({1, 3, 1, 4, 4, 3, 1}) → {1, 3, 4, 1, 1, 3, 4}
problem({3, 2, 2, 4}) → {3, 4, 2, 2}
thanks .

Set i = 0, j = 0. Then you repeat the following:
Find the first 3 at an index ≥ i which is not followed by a 4. If none are found, you succeeded. If the 3 is the last number in the array or followed by a 3, you failed. Now find the first 4 at an index ≥ j which is not preceded by a 3. If none are found, you fail. Otherwise set i = location of the 3, j = location of the 4, exchange the objects at positions i+1 and j, set i = i + 2 and j = j + 1, and repeat.
I don't like writing code that depends on promises about the data that I don't verify myself, so this will work whatever is in the array.

Related

How would you split a numpy array where the elements give the partition size?

For an numpy 1d array such as:
In [1]: A = np.array([2,5,1,3,9,0,7,4,1,2,0,11])
In [2]: A
Out[2]: array([2,5,1,3,9,0,7,4,1,2,0,11])
I need to split the array by using the values as a sub-array length.
For the example array:
The first index has a value of 2, so I need the first split to occur at index 0 + 2, so it would result in ([2,5,1]).
Skip to index 3 (since indices 0-2 were gobbled up in step 1).
The value at index 3 = 3, so the second split would occur at index 3 + 3, and result in ([3,9,0,7]).
Skip to index 7
The value at index 7 = 4, so the third and final split would occur at index 7 + 4, and result in ([4,1,2,0,11])
I'm using this simple array as an example, because I think it will help in my actual use case, which is reading data from binary files (either as bytes or unsigned shorts). I'm guessing that numpy will be the fastest way to do it, but I could also use struct/bytearray/lists or whatever would be best.
I hope this makes sense. I had a hard time trying to figure out how best to word the question.
Here is an approach using standard python lists and a while loop:
def custom_partition(arr):
partitions = []
i = 0
while i < len(arr):
pariton_size = arr[i]
next_i = i + pariton_size + 1
partitions.append(arr[i:next_i])
i = next_i
return partitions
a = [2, 5, 1, 3, 9, 0, 7, 4, 1, 2, 0, 11]
b = custom_partition(a)
print(b)
Output:
[[2, 5, 1], [3, 9, 0, 7], [4, 1, 2, 0, 11]]

Algorithm to find length of a minimal sub-array containing all the elements of an array/vector

Let's say we have an array {7, 3, 7, 3, 1, 3, 4, 1}.
What I need is an algorithm (preferably some C++ code sample) which will return length of a minimal sub-array which contains all of the array's elements.
In this case, it would be 5: {7, 3, 1, 3, 4} and this is the shortest sub-array of the original array which contains all of the array's elements, which are 1, 3, 4 and 7.
Also, one more example of the array {2, 1, 1, 3, 2, 1, 1, 3} and the algorithm should return 3 since the subarray we are looking for is {1, 3, 2} (indices 2-4 of the original array).
I found some similar question here: Find minimum length of sub-list containing all elements of a list
but it does not seem answered.
The function signature should be like:
int algorithm(std::vector<int> &arr){...}
Find last subarray in O(n) :
For example, for the array [1, 2, 3, 2, 2, 1, 1], get the counts of the items in a hash table/Map (or array for small range) : { 1: 3, 2: 3, 3: 1 }
To find the start index of the subarray, start from the first value in the array and check if it's count is more than 1. If it's count is more than 1, decrease it's count by one, and continue to next value until a value with count of 1. Repeat the same backwards to find the last index of the subarray :
1, 2, 3, 2, 2, 1, 1
^ ^
Find the rest of the subarrays in O(n) :
Now to check if that is the minimum subarray, check for subarrays before it. For that, search before the first index for the last index of the value 1 that is at the last index. If it is found, change the first index to it, and decrease the last index by one :
1, 2, 3, 2, 2, 1, 1
^ ^
Now to find the last index of the new subarray, search between the first and last index for the value 2 that is at the last index and change the last index to it :
1, 2, 3, 2, 2, 1, 1
^ ^
Repeat until the value at the last index can't be found between the first and last index :
1, 2, 3, 2, 2, 1, 1
^ ^
Now check if the count of the new subarray is less than that of the previous subarray and update the indexes of the current minimum subarray if needed.
The search for the rest of the subarrays has to be repeated until the value at the last index can't be found before the first index.

remove all negative elements from an array buffer of integers in scala

I have a question about coding. There are similar types of questions in the database which I came across but none of them clears my doubt. I am going thru the book of "Scala for Impatient". The code below removes negative elements from the Array and gives positive elements as output
val a = ArrayBuffer(-1, 1, 0, -2, -1, 2, 5, 6, 7)
val positionsToKeep = for (i <- a.indices if a(i) >= 0) yield i
for (j <- positionsToKeep.indices) a(j) = a(positionsToKeep(j))
a.trimEnd(a.length - positionsToKeep.length)
It gives the output as (1,0,2,5,6,7) removing all negative elements.
I am unable to understand line 3 & 4.
for (j <- positionsToKeep.indices) a(j) = a(positionsToKeep(j))
a.trimEnd(a.length - positionsToKeep.length)
I'm scratching my head since 2 days on these 2 lines but can't give up and I finally posting it here seeking some help.
As a is a bufferArray so we can change the values of the array a.
Line 3:
Line 3 is populating or you can say updating the value of positionToKeep into a.
a(j) = positionToKeep(j)
// which is running like this
// a(0) = positionToKeep(0)
// a(1) = positionToKeep(1) .... and so on
Now what will happen after populating all the values of positionToKeep into a there might be the case some older values remains untouched. Line four is deleting or dropping these elements. In the case when we have all the positive values in array a line four has like no use but when the length of a is greater then positionToKeep then we need line 4.
Line 4: consider the scenario
val a = Array(1, 2, 3, 4, 5, 6)
Then our positionToKeep will have all the element and the length of both the array will be equal.
val positionToKeep = Array(1, 2, 3, 4, 5, 6)
In this case line four trimEnd(0) because length of a and positionToKeep are equal.
val a = Array( 1, 2, 3, 4, -5, -6, 8, 9, -3)
In this case we will have Array(1,2,3,4,8,9) in positionToKeep
In line 3 we will update array a and after updating before line four this is how our array a will look like.
Array(1,2,3,4,8,9,8,9,-3) as we need values only up to length 6 as we have only 6 positive values. We need to drop last 3 element that what is tripEnd doing for us.

Modifying a numpy index during assignment

I am unsure of the correct terminology to search for to find the correct optimisation. I want to simplify the final four lines of code below into two lines, whereby, the addition of +/- 1 is done during the assignment to plus and minus variables respectively.
# generic params to simulate loop conditions
position = np.arange(10)
axis = 2
# actual code to optimise
plus = np.asarray(position)
plus[axis] += 1
minus = np.asarray(position)
minus[axis] -= 1
To clarify this is an iteration problem: Any solutions that don't take generic position or axis variables are wrong i.e. explicitly the following are not solutions:
plus = np.asarray([0,1,3,3,4,5,6,7,8,9])
plus = np.asarray(range(axis)+[position[axis]+1]+range(axis+1,len(position)))
Here's an approach using np.in1d to condense those four lines to two -
mask = np.in1d(np.arange(position.size),axis)
plus, minus = position + mask, position - mask
Sample run
Let's test it out for a generic position array with another index 6 -
In [60]: position
Out[60]: array([1, 0, 6, 8, 1, 7, 1, 3, 1, 6])
In [61]: axis = 6
In [62]: mask = np.in1d(np.arange(position.size),axis)
In [63]: plus, minus = position + mask, position - mask
In [64]: plus
Out[64]: array([1, 0, 6, 8, 1, 7, 2, 3, 1, 6]) # Change at 6th index
In [65]: minus
Out[65]: array([1, 0, 6, 8, 1, 7, 0, 3, 1, 6]) # Change at 6th index

How do you make every other integer in an array equal to 0 in matlab?

Lets say I have an array
Y = [1, 2, 3, 4, 5, 6]
I want to make a new array that replaces every other number with 0, so it creates
y = [1, 0, 3, 0, 5, 0]
How would I go about approaching this and writing code for this in a efficient way?
This should do that:
Y(2:2:end) = 0;
With this line you basically say each element starting from the seconds up to the last, in steps of two, should be zero. This can be done for larger steps too:, Y(N:N:end) = 0 makes every Nth element equal to 0.

Resources