iphone: how to check uitableview row modulus - iphone

it's a hard to explain issue so i hope i can state it
i have a tableview and i want that..
row number 1 have a background and row number 2 have another background .
and row number 3 have a third background..
the fourth row should have the first background and the fifth should have the second ..
and so forth ..
i used this code
if(row+1%1==0){
bg = [UIImage imageNamed:#"row1.png"];
selectionBg = [UIImage imageNamed:#"row1.png"];
}
else if(row+1%2==0){
bg = [UIImage imageNamed:#"row2.png"];
selectionBg = [UIImage imageNamed:#"row2.png"];
}else if(row+1%3==0){
bg = [UIImage imageNamed:#"row3.png"];
selectionBg = [UIImage imageNamed:#"row3.png"];
}
i'm trying to use modulus but i get lost .. so is there a way for that?
thanks in advance

You should use mod 3 because you have three options:
if (row % 3 == 0) {
// Option A
} else if (row % 3 == 1) {
// Option B
} else {
// Option C
}
By the way, do you understand what a modulo operation does? This might be interesting to read (from Wikipedia):
In computing, the modulo operation finds the remainder of division of
one number by another.
Given two positive numbers, a (the dividend)
and n (the divisor), a modulo n (abbreviated as a mod n) can be
thought of as the remainder, on division of a by n. For instance, the
expression "5 mod 4" would evaluate to 1 because 5 divided by 4 leaves
a remainder of 1, while "9 mod 3" would evaluate to 0 because the
division of 9 by 3 leaves a remainder of 0; there is nothing to
subtract from 9 after multiplying 3 times 3.
This is what happens in the code:
row row % 3 option
0 0 A
1 1 B
2 2 C
3 0 A
4 1 B
5 2 C
6 0 A
… … …

Instead of using the modulos use a static counter
Like the following
static int rowBGSelector = 0;
switch (rowBGSelector) {
case 0:
NSLog(#"%d, first", i); //Chose BG 1
break;
case 1:
NSLog(#"%d, second", i); //Chose BG 2
break;
case 2:
NSLog(#"%d, third", i); //Chose BG 3
break;
default:
rowBGSelector = -1; //Reset the static
break;
}
rowBGSelector++; //Increment

Related

Prime numbers print from range 2...100

I have been assigned with a task to print prime numbers from a range 2...100. I've managed to get most of the prime numbers but can't figure out how to get rid of 9 and 15, basically multiples of 3 and 5. Please give me your suggestion on how can I fix this.
for n in 2...20 {
if n % 2 == 0 && n < 3{
print(n)
} else if n % 2 == 1 {
print(n)
} else if n % 3 == 0 && n > 6 {
}
}
This what it prints so far:
2
3
5
7
9
11
13
15
17
19
One of effective algorithms to find prime numbers is Sieve of Eratosthenes. It is based on idea that you have sorted array of all numbers in given range and you go from the beginning and you remove all numbers after current number divisible by this number which is prime number. You repeat this until you check last element in the array.
There is my algorithm which should do what I described above:
func primes(upTo rangeEndNumber: Int) -> [Int] {
let firstPrime = 2
guard rangeEndNumber >= firstPrime else {
fatalError("End of range has to be greater than or equal to \(firstPrime)!")
}
var numbers = Array(firstPrime...rangeEndNumber)
// Index of current prime in numbers array, at the beginning it is 0 so number is 2
var currentPrimeIndex = 0
// Check if there is any number left which could be prime
while currentPrimeIndex < numbers.count {
// Number at currentPrimeIndex is next prime
let currentPrime = numbers[currentPrimeIndex]
// Create array with numbers after current prime and remove all that are divisible by this prime
var numbersAfterPrime = numbers.suffix(from: currentPrimeIndex + 1)
numbersAfterPrime.removeAll(where: { $0 % currentPrime == 0 })
// Set numbers as current numbers up to current prime + numbers after prime without numbers divisible by current prime
numbers = numbers.prefix(currentPrimeIndex + 1) + Array(numbersAfterPrime)
// Increase index for current prime
currentPrimeIndex += 1
}
return numbers
}
print(primes(upTo: 100)) // [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
print(primes(upTo: 2)) // [2]
print(primes(upTo: 1)) // Fatal error: End of range has to be greater than or equal to 2!
what is the Prime num : Prime numbers are the positive integers having only two factors, 1 and the integer itself,
//Funtion Call
findPrimeNumberlist(fromNumber: 1, toNumber: 100)
//You can print any range Prime number using this fucntion.
func findPrimeNumberlist(fromNumber:Int, toNumber: Int)
{
for i in fromNumber...toNumber
{
var isPrime = true
if i <= 1 { // number must be positive integer
isPrime = false
}
else if i <= 3 {
isPrime = true
}
else {
for j in 2...i/2 // here i am using loop from 2 to i/2 because it will reduces the iteration.
{
if i%j == 0 { // number must have only 1 factor except 1. so use break: no need to check further
isPrime = false
break
}
}
}
if isPrime {
print(i)
}
}
}
func getPrimeNumbers(rangeOfNum: Int) -> [Int]{
var numArr = [Int]()
var primeNumArr = [Int]()
var currentNum = 0
for i in 0...rangeOfNum{
currentNum = i
var counter = 0
if currentNum > 1{
numArr.append(currentNum)
for j in numArr{
if currentNum % j == 0{
counter += 1
}
}
if counter == 1{
primeNumArr.append(currentNum)
}
}
}
print(primeNumArr)
print(primeNumArr.count)
return primeNumArr
}
Then just call the function with the max limit using this
getPrimeNumbers(rangeOfNum: 100)
What is happening in above code:
The numArr is created to keep track of what numbers have been used
Any number that is prime number is added/appended to primeNumArr
Current number shows the number that is being used at the moment
We start from 0 ... upto our range where we need prime numbers upto (with little modification it can be changed if the range starts from other number beside 0)
Remember, for a number to be Prime it should have 2 divisor means should be only completely divisible by 2 numbers. First is 1 and second is itself. (Completely divisible means having remainder 0)
The counter variable is used to keep count of how many numbers divide the current number being worked on.
Since 1 is only has 1 Divisor itself hence its not a Prime number so we start from number > 1.
First as soon as we get in, we add the current number being checked into the number array to keep track of numbers being used
We run for loop to on number array and check if the Current Number (which in our case will always be New and Greater then previous ones) when divided by numbers in numArr leaves a remainder of 0.
If Remainder is 0, we add 1 to the counter.
Since we are already ignoring 1, the max number of counter for a prime number should be 1 which means only divisible by itself (only because we are ignoring it being divisible by 1)
Hence if counter is equal to 1, it confirms that the number is prime and we add it to the primeNumArr
And that's it. This will give you all prime numbers within your range.
PS: This code is written on current version of swift
Optimised with less number of loops
Considered below conditions
Even Number can not be prime number expect 2 so started top loop form 3 adding 2
Any prime number can not multiplier of even number expect 2 so started inner loop form 3 adding 2
Maximum multiplier of any number if half that number
var primeNumbers:[Int] = [2]
for index in stride(from: 3, to: 100, by: 2) {
var count = 0
for indexJ in stride(from: 3, to: index/2, by: 2) {
if index % indexJ == 0 {
count += 1
}
if count == 1 {
break
}
}
if count == 0 {
primeNumbers.append(index)
}
}
print("primeNumbers ===", primeNumbers)
I finally figured it out lol, It might be not pretty but it works haha, Thanks for everyone's answer. I'll post what I came up with if maybe it will help anyone else.
for n in 2...100 {
if n % 2 == 0 && n < 3{
print(n)
} else if n % 3 == 0 && n > 6 {
} else if n % 5 == 0 && n > 5 {
} else if n % 7 == 0 && n > 7{
} else if n % 2 == 1 {
print(n)
}
}

index in a loop by using ..<

I didn't understood the concept of the For-In loop in swift 3 , can anyone explain to us it m thanks in advance
var total = 0
for i in 0..<4 {
total += i
}
print(total)
The result of total is 6 , Why ?
i=0 =>
total = 0+0 =0
i=1 =>
total = 0+1 = 1
i=2 =>
total = 1+2 = 3
i=3 =>
total = 3+3 =6
it's simply alogrithm ;-)
i never reach 4 because you said it STRICTLY inferior to 4 =)
(Do I answer your question?)
Your loop will be vary from 0 to 3 i.e. 0,1,2,3 but if you want it will vary from 0 to 4 then try this -
var total = 0
for i in 0...4 {
total += i
}
print(total)

speed up prime number generating

I have written a program that generates prime numbers . It works well but I want to speed it up as it takes quite a while for generating the all the prime numbers till 10000
var list = [2,3]
var limitation = 10000
var flag = true
var tmp = 0
for (var count = 4 ; count <= limitation ; count += 1 ){
while(flag && tmp <= list.count - 1){
if (count % list[tmp] == 0){
flag = false
}else if ( count % list[tmp] != 0 && tmp != list.count - 1 ){
tmp += 1
}else if ( count % list[tmp] != 0 && tmp == list.count - 1 ){
list.append(count)
}
}
flag = true
tmp = 0
}
print(list)
Two simple improvements that will make it fast up through 100,000 and maybe 1,000,000.
All primes except 2 are odd
Start the loop at 5 and increment by 2 each time. This isn't going to speed it up a lot because you are finding the counter example on the first try, but it's still a very typical improvement.
Only search through the square root of the value you are testing
The square root is the point at which a you half the factor space, i.e. any factor less than the square root is paired with a factor above the square root, so you only have to check above or below it. There are far fewer numbers below the square root, so you should check the only the values less than or equal to the square root.
Take 10,000 for example. The square root is 100. For this you only have to look at values less than the square root, which in terms of primes is roughly 25 values instead of over 1000 checks for all primes less than 10,000.
Doing it even faster
Try another method altogether, like a sieve. These methods are much faster but have a higher memory overhead.
In addition to what Nick already explained, you can also easily take advantage of the following property: all primes greater than 3 are congruent to 1 or -1 mod 6.
Because you've already included 2 and 3 in your initial list, you can therefore start with count = 6, test count - 1 and count + 1 and increment by 6 each time.
Below is my first attempt ever at Swift, so pardon the syntax which is probably far from optimal.
var list = [2,3]
var limitation = 10000
var flag = true
var tmp = 0
var max = 0
for(var count = 6 ; count <= limitation ; count += 6) {
for(var d = -1; d <= 1; d += 2) {
max = Int(floor(sqrt(Double(count + d))))
for(flag = true, tmp = 0; flag && list[tmp] <= max; tmp++) {
if((count + d) % list[tmp] == 0) {
flag = false
}
}
if(flag) {
list.append(count + d)
}
}
}
print(list)
I've tested the above code on iswift.org/playground with limitation = 10,000, 100,000 and 1,000,000.

Check a multiple in Swift?

I am trying to find the odd numbers and a multiple of 7 between a 1 to 100 and append them into an array. I have got this far:
var results: [Int] = []
for n in 1...100 {
if n / 2 != 0 && 7 / 100 == 0 {
results.append(n)
}
}
Your conditions are incorrect. You want to use "modular arithmetic"
Odd numbers are not divisible by 2. To check this use:
if n % 2 != 0
The % is the mod function and it returns the remainder of the division (e.g. 5 / 2 is 2.5 but integers don't have decimals, so the integer result is 2 with a remainder of 1 and 5 / 2 => 2 and 5 % 2 => 1)
To check if it's divisible by 7, use the same principle:
if n % 7 == 0
The remainder is 0 if the dividend is divisible by the divisor. The complete if condition is:
if n % 2 != 0 && n % 7 == 0
You can also use n % 2 == 1 because the remainder is always 1. The result of any mod function, a % b, is always between 0 and b - 1.
Or, using the new function isMultiple(of:, that final condition would be:
if !n.isMultiple(of: 2) && n.isMultiple(of: 7)
Swift 5:
Since Swift 5 has been released, you could use isMultiple(of:) method.
In your case, you should check if it is not multiple of ... :
if !n.isMultiple(of: 2)
Swift 5 is coming with isMultiple(of:) method for integers , so you can try
let res = Array(1...100).filter { !$0.isMultiple(of:2) && $0.isMultiple(of:7) }
Here is an efficient and concise way of getting the odd multiples of 7 less than or equal to 100 :
let results: [Int] = Array(stride(from: 7, through: 100, by: 14))
You can also use the built-in filter to do an operation on only qualified members of an array. Here is how that'd go in your case for example
var result = Array(1...100).filter { (number) -> Bool in
return (number % 2 != 0 && number % 7 == 0)
}
print(result) // will print [7, 21, 35, 49, 63, 77, 91]
You can read more about filter in the doc but here is the basics: it goes through each element and collects elements that return true on the condition. So it filters the array and returns what you want

loop inside another loop

I have this code:
//Value of userCount is 25
auxCount = 0;
for (int y_axis=0; y_axis<=8; y_axis++) //ROWS
{
for (int x_axis=0; x_axis<=2; x_axis++) //COLUMNS
{
if (auxCount<userCount) {
NSLog(#"auxCount: %i\n",auxCount);
NSLog(#"userCount: %i\n\n",userCount);
UIButton *btn= [[UIButton alloc] initWithFrame:CGRectMake(16+100*x_axis,115.0*y_axis,88.0 ,88.0)];
UILabel *userLabel = [[UILabel alloc] initWithFrame:CGRectMake(16+100*x_axis,90+115.0*y_axis, 88.0, 15.0)];
userLabel.textAlignment = UITextAlignmentCenter;
userLabel.text = mensaje;
btn.backgroundColor=[UIColor groupTableViewBackgroundColor];
[scrollViewUsers addSubview:btn];
[scrollViewUsers addSubview:userLabel];
auxCount++;
}
}
}
With this I want a matrix with 3 columns and X rows, but only displays 3 rows and the third row only displays 1 button. And in Debug area appears:
auxCount: 0
userCount: 25
auxCount: 4
userCount: 25
auxCount: 8
userCount: 25
auxCount: 12
userCount: 25
auxCount: 16
userCount: 25
auxCount: 20
userCount: 25
auxCount: 24
userCount: 25
auxCount increments by 4 by 4. I think that is because the if instructions are executed only by the first for loop but I don't know why.
Please, I need your help.
ps: sorry for my english!!
just try this for loops as i have used in my app it worked for me.
to find out the number of rows depending on number of columns and total count
int r;
float rem = [dao libraryCount] % kCol;
if(rem == 0.0f)
r = floor([dao libraryCount]/kD);
else
r = ceil([dao libraryCount]/kD);
here r is for number if row [dao libraryCount is total number of items and kCol is fix number of column for you it is 3 and kD is same as kCol only deference is it is type of float ie 3.0 in your case
then use the for loop as below
for (int row = 0; row < r; ++row)
{
for (int col = 0; col < kCol; ++col)
{
//Your Code to display or any thing
}
}
for auxCount use this code
int index = (row * kCol) + col;
if(index < [dao libraryCount])
{
//Your Code to display or any thing
}
put this in side both for loop instead of using ++
just change the both for loops and replace if condition with appropriate variables
Enjoy Coding :)
And Good Luck
any help is needed just comment me i will love to help you