Find Specific Array Using a Loop - arrays

I'm incredibly new to swift and I'm sure this question has been asked before, but I have no idea of the terminology of what to search.
I've seen how to do this before, but not sure where. I want to be able to loop though my arrays using a count, like the below (but that is not working). So the last number of the array name changes depending on the count. So if myCount = 0 then myArray will equal array_0001_00 and if my count = 6 then myArray will equal array_0001_06, and so on.
I'm not sure if I'm missing something small or if I'm completely on the wrong track.
let array_0001_00 = [102,102,102,102,102,102,102,102]
let array_0001_01 = [112,112,112,112,112,112,112,112]
myArray = array_0001_0\(myCount)
Any help would be much appreciated. Thanks.
I'm currently using the below, which works, but is creating a mountain of code:
if myCount == 0 {
myArray = array_0001_00
} else if myBuilderCountY == 1 {
myArray = array_0001_01
}

I hope I haven't misunderstood - you have a number of arrays, and you want to select one of them using an index. That looks like selecting an element from an array:
let array_0001_00 = [102,102,102,102,102,102,102,102]
let array_0001_01 = [112,112,112,112,112,112,112,112]
let array_0001_02 = [122,122,122,122,122,122,122,122]
let array_of_arrays = [
array_0001_00,
array_0001_01,
array_0001_02
]
let index = 1
let myArray = array_of_arrays[index] // This assigns (a copy of) array_0001_01

Related

Search and replace string in 2D Array in Swift

Teaching myself swift, so complete noob here, but I'm far into a project and just know there must be an easier way to achieve something.
I have a 2D array:
var shopArray = [
["theme":"default","price":0,"owned":true,"active":true,"image":UIImage(named: "defaultImage")!,"title":"BUY NOW"],
["theme":"red","price":1000,"owned":false,"active":false,"image":UIImage(named: "redImage")!,"title":"BUY NOW"],
["theme":"blue","price":2000,"owned":false,"active":false,"image":UIImage(named: "blueImage")!,"title":"BUY NOW"],
["theme":"pool","price":3000,"owned":true,"active":false,"image":UIImage(named: "blueImage")!,"title":"BUY NOW"],
["theme":"line","price":4000,"owned":false,"active":false,"image":UIImage(named: "lineImage")!,"title":"BUY NOW"],
["theme":"neon","price":5000,"owned":false,"active":false,"image":UIImage(named: "lineImage")!,"title":"BUY NOW"]]
Where I simply want to create a function that runs and search for all the "owned" keys and make them all "false".
How do you search and replace in Arrays / 2D Arrays. More specifiaclly, what should the func look like?
Thank you!
You don't have a 2D array, you have an Array of Dictionaries.
You can set all of the values for the owned keys by iterating the indices of the Array and updating the values:
shopArray.indices.forEach { shopArray[$0]["owned"] = false }
That is the functional way to do it. You could also do the same operation with a for loop:
for idx in shopArray.indices {
shopArray[idx]["owned"] = false
}
You could do something like this to loopthrough the array replacing the approriate element.
var i = 0
for x in shopArray {
var y = x
y["owned"] = false
shopArray.remove(at: i)
shopArray.insert(y, at: i)
i = i + 1
}
or you could use a while loop to do the same with less code lines.
var y = 0
while y < shopArray.count {
shopArray[y].updateValue(false, forKey: "owned")
y += 1
}
There is proably somthing doable with .contains, but I'm not sure you need that toachive the result you mention above. Play around in a play ground in xcode and try a few different options without doing anything that might cause issues in your project.

finding a str in MatLab cells

I am currently using MatLab R2014a
I have one array and one cell:
MyArray = ['AA1', 'AA2', 'AB1', 'AB2', 'Acc1', 'Acc2'];
MyCell = {'Name1AA1', 'Name2AA1', 'Name3Acc2', 'Name4AB2', 'Name5AD1};
MyArray consists of code names that are repeatable throughout MyCell.
I would like to check if any of the strings in MyArray are in MyCell and if it is, save the name to a new cell.
For now I have:
NewCell = {};
for i = 1:length(MyCell)
for j = 1:length(MyArray)
Find = strfind(MyCell(i), MyArray)
if ~isempty(Find)
NewCell = {NewCell; MyCell(j)}
end
end
end
However, when I use strfind I get this error message:
Undefined function 'strfind' for input arguments of type 'char'
If I use strcmp instead of strfind, I get an array of everything in MyCell repeated by the number of elements in MyArray.
My Ideal output would be:
NewCell1 = {'Name1AA1', 'Name2AA1'}
NewCell2 = {'Name4AB2'}
NewCell3 = {'Name3Acc2'}
ie, no new cell for the code names that are not present in MyArray or no new cell if there is a code name in MyArray but not in MyCell.
Any help is welcome, and thanks for your time
You can use a combination of regular expressions to achieve the desired output. Your approach of wanting to name variables dynamically is not recommended and will lead to code which is harder to debug. Use indexing instead.
You can read this informative post on Matlab's forum to understand why.
%Your input data.
MyArray = ['AA1', 'AA2', 'AB1', 'AB2', 'Acc1', 'Acc2'];
MyCell = {'Name1AA1', 'Name2AA1', 'Name3Acc2', 'Name4AB2', 'Name5AD1'};
%Find common elements between MyArray and MyCell.
elem = cellfun(#(x) regexp(MyArray,x(end-2:end),'match'),MyCell,'un',0);
%Eliminate duplicates.
NewCell = unique([elem{:}]);
%Find elements in MyCell which end with NewCell elements and group them.
NewCell = cellfun(#(x) regexp([MyCell{:}],strcat('Name\d\w?',x),'match'),NewCell,'un',0);
%Join elements.
NewCell{1} = {strjoin(NewCell{1},''',''')};
NewCell{1} = {'Name1AA1','Name2AA1'}
NewCell{2} = {'Name4AB2'}
NewCell{3} = {'Name3Acc2'}

How do I pull out certain words from a string?

I have two arrays of strings that I join together with a "-" separator which turns it into a full string like so "art-movies-sports". The code is below:
let myFirstArray: [String] = ["art", "movies", "sports"]
let firstJoinedArray = myFirstArray.joined(separator: "-")
let mySecondArray: [String] = ["art", "movies", "sports"]
let secondJoinedArray = mySecondArray.joined(separator: "-")
What I want is to call something when 3 or more words from "art-movies-sports" in firstJoinedArray are equal to 3 or more words in secondJoinedArray. In this case, it will of course be correct. In a nutshell, I want to have much longer strings (both containing different words but have 3 or 4 that are the same) and I want to call something when 3 or more are correct. Any help will be much appreciated! Thank you.
I would use the arrays directly, rather than the string. Then create sets out of them, so you can find their intersection:
let set1 = Set(myFirstArray)
let set2 = Set(mySecondArray)
let inCommon = set1.intersection(set2).count // If this is >= 3, do stuff

Replacing repeated values of cell with empty [] - MATLAB

So I have a 1x348 cell composed of numbers and empty brackets. Ie ... [] [] [] [169] [170] [170] [170] [171] [172] [] []...
All what I want to do is change the repeated numbers to empty brackets []. I need to hold the places. I tried this, but am not having any success. It is also not ideal, because in the case with more than one repeat, it would just replace every other repeat with [].
for jj = 1:length(testcell);
if testcell{jj} == testcell{jj-1}
testcell{jj} = []
end
Any help would be greatly appreciated :-)
Lets assume you have {1,1,1}. First iteration will change this to {1,[],1} and second iteration does not see any repetition. Thus iterating backwards is probably the easiest solution:
for jj = length(testcell):-1:2
if testcell{jj} == testcell{jj-1}
testcell{jj} = [];
end
end
Then the first step will result in {1,1,[]} and the second in {1,[],[]}
The only thing your code lacks is some variable to store current value:
current = testcell{1};
for jj = 2:length(testcell)
if testcell{jj} == current
testcell{jj} = [];
else
current = testcell{jj};
end
end
But it's better to use Daniel's solution =).
Alternatively, you could use NaN values to represent cells with empty matrices, and vectorize your code:
testcell(cellfun('isempty', testcell)) = {NaN};
[U, iu] = unique([testcell{end:-1:1}]);
testcell(setdiff(1:numel(testcell), numel(testcell) - iu + 1)) = {NaN};
testcell(cellfun(#isnan, testcell)) = {[]};

Cannot convert error when assigning array to a range

Below is my code and on the last line of code I get a "Cannot convert error". To clarify the line: sheet.getRange throws the error.
That is all the error says; nothing more, just "Cannot convert". Also, this is the full code, so there is nothing else.
function days(){
var table = new Array(7);
for ( var i = 0; i < 7 ; i ++){
table[i] = i+2;
}
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Want");
sheet.getRange("B2:B9").setValues(table);
}
I don't know anything about Google Apps Scripting, but I managed to find this on Google.
It appears your table needs to be a 2-dimensional array.
Perhaps this can help?
(code is from the link above)
var myTable = [[1, 2, 3, 4],[5, 6, 7, 8]];
var sheet = SpreadsheetApp.getActiveSheet();
sheet.getRange(1,1,2,4).setValues(myTable);
SetValues() takes a 2 dimensions array as argument, TABLE is a 1 dimension array... this cannot work as it is... It's easy to change though, make table a 2D array of 7 elements.
like this : table[i] = [i+2];
btw, range ('B2:B9') is 8 cells high and you only give 7 values... there will be a problem there !
I figured out the problem to this question, so I will answer the question so that others may benefit. The problem here is that the .setValues method for a Range object must be given a two dimensional array [][]. So I created a 0 dimensional array inside of the other one so that i now had a two dimensional array.
var array = new Array(7);
for (var i = 0; i < 7; i++) {
array[i] = new Array(0);
}

Resources