how to rearrange array using objective c? - ios

I am new in objective c. I have array please see sample. I need to
rearrange from 1,2,3 to 2,3,1. Thank you guys.
"M 90.5, 88", <- please pay attention to this
" C",
"84.083333373069763, 96.083333253860474", <- 1;
"87.5, 90.333333253860474", <- 2;
"84.5, 92.666666507720947", <- 3;
"M 171, 204", <- please pay attention to this
" C",
"161, 199.50000002980232", <- 1;
"168, 202.33333337306976", <- 2;
"165, 200.66666674613953", <- 3;
" C",
"153.16666674613953, 215.25", <- 1;
"148.5, 202.66666650772095", <- 2;
"150, 208.33333301544189", <- 3;
" C",
"136.5, 249", <- 1;
"146.83333349227905, 246.66666662693024", <- 2;
"141.66666698455811, 247.83333325386047" <- 3;
This is my code before and it works in a single Starting point(moveTO) only. what if I draw lots of lines it will create mutliple starting points
like
"M 82, 130.5 ",
" 76.333333253860474, 137.16666674613953 ",
" 78.833333253860474, 132.66666674613953 ",
" 75.666666507720947, 134.83333349227905 ",
" 86, 144.5 ",
" 77, 139.5 ",
" 81.5, 142",
"M 146, 137.5 ",
" 147.25, 152.66666674613953 ",
" 146.83333331346512, 142.5 ",
" 147.66666662693024, 147.5 ",
" 141.83333337306976, 166.08333349227905 ",
" 146.83333337306976, 157.83333349227905 ",
" 145.16666674613953, 163.16666698455811 ",
" 128.5, 170 ",
" 138.5, 169 ",
" 133.5, 169.5"
NSArray *myArray = #[#"M 198.16666666418314, 199.75",#"203.5, 198.5", and so on... ];
NSMutableArray *newArray = [NSMutableArray arrayWithArray:myArray];
for(int i=1;i<[newArray count];i=i+3) {
[newArray exchangeObjectAtIndex:i withObjectAtIndex:i+2];
[newArray exchangeObjectAtIndex:i withObjectAtIndex:i+1];
}

I figure it out. thanks guys.
for(int i=1;i<[newArray count];i++) {
NSString *strMovTo2 = [newArray objectAtIndex:i];
NSArray *elements2 = [strMovTo2 componentsSeparatedByString:#"-"];
newArray2 = [NSMutableArray arrayWithArray:elements2];
for(int j=1;j<[newArray2 count];j=j+3) {
[newArray2 exchangeObjectAtIndex:j withObjectAtIndex:j+2];
[newArray2 exchangeObjectAtIndex:j withObjectAtIndex:j+1];
}
newArray3 = [[NSMutableArray alloc] init];
for (int y = 2; y<[newArray2 count]; y=y+3){
[newArray3 addObject: [NSString stringWithFormat:#"%# %# %#", newArray2[y-1], newArray2[y], newArray2[y+1] ]];
}
curves = [newArray3 componentsJoinedByString:#" C "];
MovTOstart = [NSString stringWithFormat:#"-M %# C", newArray2[0]];
[svgFileToPast appendFormat:#"%# %#", MovTOstart, curves];
}

Related

General insertion sort algorithm not moving the first object in list

I need to create a general insertion sort algorithm using move semantics. I have it working for entire lists of different types of objects except for the very first object in the list.
template<typename Iter, typename Comparator>
void insertionSort(const Iter& begin, const Iter& end, Comparator compareFn)
{
for (auto i = begin + 1; i < end; i++)
{
auto currentthing = std::move(*i);
auto j = std::move(i - 1);
while (j >= begin and compareFn(*j, currentthing))
{
*(j + 1) = std::move(*j);
if (j == begin)
break;
j--;
}
*(j + 1) = std::move(currentthing);
}
}
Where comparing a list of strings from my main function:
int main()
{
vector<int> numbers = { 0, 1, 8, 4, 2, 9, 5, 3, 6, 7, 10 };
insertionSort(numbers.begin(), numbers.end(), std::less<int>());
cout << "Sorted: " << numbers << "\n";
vector<string> names = { "p", "a", "b", "d", "c", "f", "e" };
insertionSort(names.begin(), names.end(), std::greater<string>());
cout << "Sorted: " << names << "\n";
return 0;
}
Outputs the following
Sorted: [ 0 10 9 8 7 6 5 4 3 2 1 ]
Sorted: [ a b c d e f ]
The while loop should break when j equals i and not when j equals begin. So, the following:
if (j == begin)
break;
should actually be:
if (j == i)
break;

IBAN Validator Swift

I am writing an algorithm to validate IBAN (International Bank Account Number) in Swift 3 and not able to figure one of the validation.
Example IBAN - BE68539007547034
Here are the rules to validate -
Input number should be of length 16.
First 2 characters are country code (not numeric).
Last 14 are numeric.
Last 2 characters are the modulo 97 result of the previous 12 numeric characters.
While #1 - #3 are clear I need clarity on #4. If anyone have done this before and know about it then please let me know.
The validation algorithm is rather simple if you follow the algorithm on wikipedia:
extension String {
private func mod97() -> Int {
let symbols: [Character] = Array(self)
let swapped = symbols.dropFirst(4) + symbols.prefix(4)
let mod: Int = swapped.reduce(0) { (previousMod, char) in
let value = Int(String(char), radix: 36)! // "0" => 0, "A" => 10, "Z" => 35
let factor = value < 10 ? 10 : 100
return (factor * previousMod + value) % 97
}
return mod
}
func passesMod97Check() -> Bool {
guard self.characters.count >= 4 else {
return false
}
let uppercase = self.uppercased()
guard uppercase.range(of: "^[0-9A-Z]*$", options: .regularExpression) != nil else {
return false
}
return (uppercase.mod97() == 1)
}
}
Usage:
let iban = "XX0000000..."
let valid = iban.passesMod97Check()
If you want to validate the format for a specific country, just modify the regular expression, e.g.
"^[A-Z]{2}[0-9]{14}$"
or directly
"^BE\\d{14}$"
From Wikipedia
let IBAN = "GB82WEST12345698765432" // uppercase, no whitespace !!!!
var a = IBAN.utf8.map{ $0 }
while a.count < 4 {
a.append(0)
}
let b = a[4..<a.count] + a[0..<4]
let c = b.reduce(0) { (r, u) -> Int in
let i = Int(u)
return i > 64 ? (100 * r + i - 55) % 97: (10 * r + i - 48) % 97
}
print( "IBAN \(IBAN) is", c == 1 ? "valid": "invalid")
prints
IBAN GB82WEST12345698765432 is valid
With IBAN from your question it prints
IBAN BE68539007547034 is valid
I finded a great solution that work for me in Objective-C
https://gist.github.com/0xc010d/5301790 you can rewrite for Swift or use bridging header. Objective-C implementation of mod97 IBAN checking algorithm
#import <Foundation/Foundation.h>
#interface NSString (Mod97Check)
- (BOOL)passesMod97Check; // Returns result of mod 97 checking algorithm. Might be used to check IBAN.
// Expects string to contain digits and/or upper-/lowercase letters; space and all the rest symbols are not acceptable.
#end
#import "NSString+Mod97Check.h"
#implementation NSString (Mod97Check)
- (BOOL)passesMod97Check {
NSString *string = [self uppercaseString];
NSInteger mod = 0, length = [self length];
for (NSInteger index = 4; index < length + 4; index ++) {
unichar character = [string characterAtIndex:index % length];
if (character >= '0' && character <= '9') {
mod = (10 * mod + (character - '0')) % 97; // '0'=>0, '1'=>1, ..., '9'=>9
}
else if (character >= 'A' && character <= 'Z') {
mod = (100 * mod + (character - 'A' + 10)) % 97; // 'A'=>10, 'B'=>11, ..., 'Z'=>35
}
else {
return NO;
}
}
return (mod == 1);
}
#end
-(BOOL)isValidIBAN {
NSString *iban = self;
static NSString* const LettersAndDecimals = #"ABCDEFGHIJKLKMNOPQRSTUVWXYZ0123456789";
iban = [[iban stringByReplacingOccurrencesOfString:#" " withString:#""] uppercaseString];
NSCharacterSet *invalidChars = [[NSCharacterSet characterSetWithCharactersInString:LettersAndDecimals] invertedSet];
if ([iban rangeOfCharacterFromSet:invalidChars].location != NSNotFound)
{
return NO;
}
int checkDigit = [iban substringWithRange:NSMakeRange(2, 2)].intValue;
iban = [NSString stringWithFormat:#"%#%#",[iban substringWithRange:NSMakeRange(4, iban.length - 4)], [iban substringWithRange:NSMakeRange(0, 4)]] ;
for (int i = 0; i < iban.length; i++) {
unichar c = [iban characterAtIndex:i];
if (c >= 'A' && c <= 'Z') {
iban = [NSString stringWithFormat:#"%#%d%#", [iban substringWithRange:NSMakeRange(0, i)], (c - 'A' + 10),[iban substringWithRange:NSMakeRange(i+1, iban.length - i - 1)]];
}
}
iban = [[iban substringWithRange:NSMakeRange(0, iban.length - 2)] stringByAppendingString:#"00"];
while(true)
{
int iMin = (int)MIN(iban.length, 9);
NSString* strPart = [iban substringWithRange:NSMakeRange(0, iMin)];
int decnumber = strPart.intValue;
if(decnumber < 97 || iban.length < 3)
break;
int del = decnumber % 97;
iban = [NSString stringWithFormat:#"%d%#", del, [iban substringFromIndex:iMin]];
}
int check = 98 - iban.intValue;
return checkDigit == check;
}
Here you go :
func isValidIBAN(text:String) -> Bool {
let ibanRegEx = "[a-zA-Z]{2}+[0-9]{2}+[a-zA-Z0-9]{4}+[0-9]{7}([a-zA-Z0-9]?){0,16}"
let ibanTest = NSPredicate(format:"SELF MATCHES %#", ibanRegEx)
return ibanTest.evaluate(with: text)
}
It's clean, and it works.

How to convert UPC-A to UPC-E?

We would like to convert the 12 digit UPC-A to 8 digit UPC-E. Can you tell me which is the best way to do this without having to use my own code to convert?
I got many formula for convert the 8 digit UCC-E to 12 digit UPC-A but not reverse.
The algorithm for converting a GTIN-12 identifier between UPC-A and UPC-E representation can be most clearly seen from the following pattern mapping:
SabN0000cdeX ⟺ SabcdeNX : 0≤N≤2
Sabc00000deX ⟺ Sabcde3X
Sabcd00000eX ⟺ Sabcde4X
Sabcde0000NX ⟺ SabcdeNX : 5≤N≤9
In the above S is the number system, either 0 or 1 and X is the check digit. If a UPC-A doesn't match a pattern then it cannot be converted to UPC-E.
It can be seen that there may be up to four valid UPC-E representations of each UPC-A:
001200000067 ⟺ 00100627 ⟺ 00120637 ⟺ 00120647 ⟺ 00120067.
Pseudo-code performing one method of conversion from UPC-A to UPC-E looks like this:
Input: A valid twelve-digit UPC-A: Assigned to A[].
Output: PASS: Eight-digit UPC-E representing the UPC-A.
FAIL: Reason.
if A[0] != {0-1} then FAIL: Invalid number system.
if A[3] == {0-2} && A[4..7] == "0000" then PASS: A[0..2] . A[8..10] . A[3] . A[11]
if A[4..8] == "00000" then PASS: A[0..3] . A[9..10] . "3" . A[11]
if A[5..9] == "00000" then PASS: A[0..4] . A[10] . "4" . A[11]
if A[6..9] == "0000" && A[10] == {5-9} then PASS: A[0..5] . A[10] . A[11]
otherwise, FAIL: UPC-A not compatible with UPC-E.
NSString *strScannedCode = #"028200002921";
NSString *strBarCodeType = #"UPC E";
NSString *strAlteredScannedCode = strScannedCode;
if ([strBarCodeType isEqualToString:#"UPC E"])
{
if (strScannedCode.length == 12)
{
NSString *strManufacturerCode = [strScannedCode substringWithRange:(NSMakeRange(1, 5))];
NSString *strProductCode = [strScannedCode substringWithRange:NSMakeRange(6, 5)];
NSLog(#"strManufacturerCode = %#",strManufacturerCode);
NSLog(#"strProductCode = %#",strProductCode);
if ([[strManufacturerCode substringWithRange:NSMakeRange(2, 3)] isEqualToString:#"000"] ||
[[strManufacturerCode substringWithRange:NSMakeRange(2, 3)] isEqualToString:#"100"] ||
[[strManufacturerCode substringWithRange:NSMakeRange(2, 3)] isEqualToString:#"200"])
{
strAlteredScannedCode = STRING(#"%#%#%#",[strManufacturerCode substringWithRange:NSMakeRange(0, 2)],
[strProductCode substringWithRange:NSMakeRange(2, 3)],
[strManufacturerCode substringWithRange:NSMakeRange(2, 1)]);
}
else if ([[strManufacturerCode substringWithRange:NSMakeRange(3, 2)] isEqualToString:#"00"])
{
strAlteredScannedCode = STRING(#"%#%#3",[strManufacturerCode substringWithRange:NSMakeRange(0, 3)],
[strProductCode substringWithRange:NSMakeRange(3, 2)]);
}
else if ([strManufacturerCode characterAtIndex:4] == '0')
{
strAlteredScannedCode = STRING(#"%#%#4",[strManufacturerCode substringWithRange:NSMakeRange(0, 4)],
[strProductCode substringWithRange:NSMakeRange(4, 1)]);
}
else if ([strManufacturerCode characterAtIndex:4] != '0')
{
strAlteredScannedCode = STRING(#"%#%#",strManufacturerCode,
[strProductCode substringWithRange:NSMakeRange(4, 1)]);
}
strAlteredScannedCode = STRING(#"%#%#%#",[strScannedCode substringWithRange:NSMakeRange(0, 1)],strAlteredScannedCode,[strScannedCode substringWithRange:NSMakeRange(11, 1)]);
NSLog(#"strUPC_E_Code = %#",strAlteredScannedCode);
}
}
By implementing above code you will get 12 digit to 8 digit, For Example you will get result as "02829221", This is UPC E of "028200002921".

get average index of objects that are in an array of arrays

I have an array of an array of objects. The inner arrays have been sorted in order then added to an overall array. All the inner objects are the same thing with different values.
I am trying to go through those arrays and organize the objects in order from the average index value.
Example of the inner arrays sorted
obj 1 | obj 2 | obj 2
obj 2 | obj 1 | obj 1
obj 3 | obj 3 | obj 4
obj 4 | obj 4 | obj 3
then the output i would need from that after getting the average would be
obj 2
obj 1
obj 3
obj 4
I really only need the top three index averages but I would like to get all of them. So for example to get 3 I could do this
for (NSArray* innerArray in outterArray) {
for (NSString* str in innerArray) {
if ([innerArray indexOfObject:str] == 0) {
[first addObject:str];
}else if([innerArray indexOfObject:str] == 1){
[second addObject:str];
}else if ([innerArray indexOfObject:str] == 2){
[third addObject:str];
}
}
}
Then go through those three arrays and see what pops up where but there must be a better way of doing this and its probably something simple but I cant see it
All objects occur the same number of times, therefore you can compute the sum
of indices instead of the average for each object.
This can be done by enumerating once over all inner dictionaries, and updating
a hash map (dictionary) with the sum of indices for the current object.
(Note that indexOfObject:
is not needed here to locate the objects in the inner array.)
Then sort the objects according to the sum of the indices (which is the value
of the object in the dictionary):
NSArray *outerArray = #[
#[#"obj 1", #"obj 2", #"obj 3", #"obj 4"],
#[#"obj 2", #"obj 1", #"obj 3", #"obj 4"],
#[#"obj 2", #"obj 1", #"obj 4", #"obj 3"],
];
NSMutableDictionary *map = [NSMutableDictionary dictionary];
for (NSArray *innerArray in outerArray) {
NSUInteger index = 0; // Index of next object in the inner array
for (NSString *str in innerArray) {
// Add current index of this object to previous sum and update hash map
NSUInteger tmp = index + [map[str] unsignedIntegerValue];
map[str] = #(tmp);
index++;
}
}
NSArray *sorted = [[map allKeys] sortedArrayUsingComparator:^NSComparisonResult(NSString *obj1, NSString *obj2) {
return [map[obj1] compare:map[obj2]];
}];
NSLog(#"%#", sorted);
Output:
(
"obj 2",
"obj 1",
"obj 3",
"obj 4"
)
The dictionary map in this case is
{
"obj 1" = 2; // "obj 1" at indices 0 + 1 + 1
"obj 2" = 1; // "obj 2" at indices 1 + 0 + 0
"obj 3" = 7; // "obj 3" at indices 2 + 2 + 3
"obj 4" = 8; // "obj 4" at indices 3 + 3 + 2
}

Export rich text format from TFS to Excel

I am trying to export TFS 2012 test cases to excel.
currently I was able to export the data to excel as plain text with the following code
foreach (ITestCase Testcase in testcases)
{
int j = 1;
string str1 = null;
string str2 = null;
foreach (ITestAction action in Testcase.Actions)
{
ISharedStep shared_step = null;
ISharedStepReference shared_ref = action as ISharedStepReference;
if (shared_ref != null)
{
shared_step = shared_ref.FindSharedStep();
foreach (ITestAction shr_action in shared_step.Actions)
{
var test_step = shr_action as ITestStep;
str1 = str1 + j.ToString() + "." + ((test_step.Title.ToString().Length ==0)? "<<Not Recorded>>" : test_step.Title.ToPlainText()) + System.Environment.NewLine;
str2 = str2 + j.ToString() + "." + ((test_step.ExpectedResult.ToString().Length ==0) ? "<<Not Recorded>>" : test_step.ExpectedResult.ToPlainText()) + System.Environment.NewLine;
j++;
}
}
else
{
var test_step = action as ITestStep;
str1 = str1 + j.ToString() + "." + ((test_step.Title.ToString().Length ==0) ? "<<Not Recorded>>" : test_step.Title.ToPlainText()) + System.Environment.NewLine;
str2 = str2 + j.ToString() + "." + ((test_step.ExpectedResult.ToString().Length ==0) ? "<<Not Recorded>>" : test_step.ExpectedResult.ToPlainText()) + System.Environment.NewLine;
j++;
}
}
oSheet.Cells[i, 1].Value = Testcase.Id.ToString();
oSheet.Cells[i, 2].Value = Testcase.Title.ToString();
oSheet.Cells[i, 3].Value = str1;
oSheet.Cells[i, 4].Value = str2;
ParameterizedString Description = Testcase.Description;
oSheet.Cells[i, 5].Value = Description.ToPlainText();
i++;
}
I'm using EPPlus.dll to write to the excel file.
My Question is how to export formatted text?
Why you are trying to code it?
Download "test case extractor" to excel and export all test cases to excel sheets.

Resources