Trying to add objects inside empty NSMutableArray at different indices in iOS - nsmutablearray

I have an application where I am working with an array of words, and each word needs to be in a particular index of the array. I have another array that holds the corresponding indices for each word. When I iterate through the first array, and try to add the word to the second array in the index found in the index array, I am getting the following runtime exception:
'NSRangeException', reason: '*** -[__NSArrayM insertObject:atIndex:]: index 1 beyond bounds for empty array'
My code is as follows:
for (int i = 0; i < [wordList count]; i++) {
[wordTypeList insertObject:[wordList objectAtIndex:i] atIndex:[[sort objectAtIndex:i] intValue]];
}
Where wordList is my initial array, sort is the array that holds numbers that represent the indices for each word, and wordTypeList is the second array that is holding the array in the correct order.
What is it that I am doing wrong?

Related

Sub arrays in python

How to print the sum of user desired subarray from a given list [1,2,3,4,5,6] using slice method in python ?
I've got success till the slice method and displaying the subarray , but I am not able to do the sum operation as it is showing error for data type of list i.e. string.
You can use the builtin function sum or do it manually by:
arr= []
sum= 0
for i in range(len(subarr)):
sum+= subarr[i]
arr.append(sum)
return arr

Sorting algoritm

I want to make my algorithm more efficient via deleting the items it already sorted, but i don't know how I can do it efficiently. The only way I found was to rewrite the whole list.
l = [] #Here you put your list
sl = [] # this is to store the list when it is sorted
a = 0 # variable to store which numbers he already looked for
while True: # loop
if len(sl) == len(l): #if their size is matching it will stop
print(sl) # print the sorted list
break
a = a + 1
if a in l: # check if it is in list
sl.append(a) # add to sorted list
#here i want it to be deleted from the list.
The variable a is a little awkward. It starts at 0 and increments 1 by 1 until it matches elements from the list l
Imagine if l = [1000000, 1200000, -34]. Then your algorithm will first run for 1000000 iterations without doing anything, just incrementing a from 0 to 1000000. Then it will append 1000000 to sl. Then it will run again 200000 iterations without doing anything, just incrementing a from 1000000 to 1200000.
And then it will keep incrementing a looking for the number -34, which is below zero...
I understand the idea behind your variable a is to select the elements from l in order, starting from the smallest element. There is a function that does that: it's called min(). Try using that function to select the smallest element from l, and append that element to sl. Then delete this element from l; otherwise, the next call to min() will select the same element again instead of selecting the next smallest element.
Note that min() has a disadvantage: it returns the value of the smallest element, but not its position in the list. So it's not completely obvious how to delete the element from l after you've found it with min(). An alternative is to write your own function that returns both the element, and its position. You can do that with one loop: in the following piece of code, i refers to a position in the list (0 is the position of the first element, 1 the position of the second, etc) and a refers to the value of that element. I left blanks and you have to figure out how to select the position and value of the smallest element in the list.
....
for i, a in enumerate(l):
if ...:
...
...
If you managed to do all this, congratulations! You have implemented "selection sort". It's a well-known sorting algorithm. It is one of the simplest. There exist many other sorting algorithms.

Selection Sort in Python not sorting

I wrote a program for selection sort by first creating a function that finds the minimum element in the array. Then I iterate through the array placing the smallest element in the correct place in the array while replacing the smallest element.
This is my code :
a=[int(input()) for _ in range(6)]
def smallest_element(arr,x):
smallest = arr[x]
d = x
for j in range(x+1,len(arr)):
if arr[j] < smallest:
smallest = arr[j]
d = j
return d
for i in range(0,len(a)):
c = a[i]
if(c > a[smallest_element(a,i)]):
a[i] = a[smallest_element(a,i)]
a[smallest_element(a,i)] = c
print(a)
But the problem is my array is not getting sorted.
Input - [5,2,4,6,1,3]
Output - [5,2,4,6,1,3]
The error seems to be in your loop.
You assign the smallest value found to the current index.
a[i] = a[smallest_element(a,i)]
You then assign the value that was originally stored to the index where the smallest element is located.
a[smallest_element(a,i)] = c
You do however re-calculate the index of the smallest element, which always is the current index - because you just copied the smallest value to the current index.
first approach
I know of two solutions to this problem. First you may only search the index of the smallest element once per loop round. That way you do not re-calculate the index and write to the correct position.
for i in range(0, len(a)):
c = a[i]
indexOfSmallestElement = smallest_element(a, i)
smallestElement = a[indexOfSmallestElement]
if c > smallestElement:
a[i] = smallestElement
a[indexOfSmallestElement] = c
second approach
Another solution is to search the element starting from the current index + 1 instead of the current index, and thus skipping the entry that you've already changed.
Exchange a[smallest_element(a, i)] = c with a[smallest_element(a, i + 1)] = c.
I do however recommend to use the first approach as it recudes the amount of times the array is iterated over.
First, in your code, you have called the smallest_element(arr,x) 3 times which will consume more time for larger arrays. Instead we can store that value to a variable rather calling 3 times.
Secondly you are swapping 2 times one in function body and in if block.
So in the function body , find the current smallest element. Then return that index to main.Then if it is smaller than the present element (in the main for loop), then swap it.
#Find the smallest element
def smallest_element(arr,x):
small = x
for j in range(x+1,len(arr)):
if arr[j] < arr[small]:
small=j
return small
#now compare it with the current element
for i in range(0,len(a)):
c = a[i]
curr=smallest_element(a,i)
if(c > a[curr] and curr!=i):
a[i] = a[curr]
a[curr] = c
print(a)

How to change diagonal elements in a matrix

I'm trying to change elements of the diagonal(1) of a matrix but I can't do it because of the error "assignment destination is read-only.
x=np.loadtxt('matrice.txt')
print(x.diagonal(1)) #2
x.diagonal(1)[0]=3
ValueError: assignment destination is read-only
In numpy docs for diagonal it is said
Starting in NumPy 1.9 it returns a read-only view on the original
array. Attempting to write to the resulting array will produce an
error.
In some future release, it will return a read/write view and writing
to the returned array will alter your original array. The returned
array will have the same type as the input array.
If you don’t write to the array returned by this function, then you
can just ignore all of the above.
If you depend on the current behavior, then we suggest copying the
returned array explicitly, i.e., use np.diagonal(a).copy() instead of
just np.diagonal(a). This will work with both past and future versions
of NumPy.
So you should use np.diagonal(a).copy() to get modifiable array.
If you need to edit a diagonal of your matrix you can use this answer by Hans Then.
def kth_diag_indices(a, k):
rows, cols = np.diag_indices_from(a)
if k < 0:
return rows[-k:], cols[:k]
elif k > 0:
return rows[:-k], cols[k:]
else:
return rows, cols
x[kth_diag_indices(x,1)] = 2 # to make them all equal to 2

String arrays with linear time lookup

I am doing string processing in Matlab and I usually use cell arrays to store individual words in the text
Example:
a = {'this', 'is', 'an', 'array', 'of', 'strings'}
For searching for the word 'of' in this array I loop through the array and check each individual element against my word. This method does not scale since if I get a large dataset my array a will grow large and looping through elements is not wise. I am wondering if there is any more smart way, perhaps a better native data structure in Matlab, that can help me run this faster?
A map container is one option. I don't know what specific sort of string processing you intend to do, but here's an example for how you can store each string as a key which is associated with a vector of index positions of that word in a cell array:
a = {'this', 'is', 'an', 'array', 'of', 'strings', 'this', 'is'};
strMap = containers.Map(); %# Create container
for index = 1:numel(a) %# Loop over words to add
word = a{index};
if strMap.isKey(word)
strMap(word) = [strMap(word) index]; %# Add to an existing key
else
strMap(word) = index; %# Make a new key
end
end
You could then get the index positions of a word:
>> indices = strMap('this')
indices =
1 7 %# Cells 1 and 7 contain 'this'
Or check if a word exists in the cell array (i.e. if it is a key):
>> strMap.isKey('and')
ans =
0 %# 'and' is not present in the cell array

Resources