Create multiplication table with swift - swift

im a beginner here. Ive been stuck on a problem for some time now. Practicing in playground and i need to make a multiplication table.
basically, if i input 3, i want the table to read
1 2 3
2 4 6
3 6 9
Im confused on the loop for this though. Any help please?
Code so far
var x = 3
var width = 1
for x in 1...x {
for width in 1...width {
print(x, width*2)
}
}
this code prints
1 2
2 2
3 2

You could do it like this.
func multiplicationTable(till limit: Int) {
for i in 1...limit {
for j in 1...limit {
print(i * j, terminator: "\t")
}
print("")
}
}
multiplcationTable(till: 5)
Output
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25

If conciseness is paramount:
let x = 3
let range = 1...x
for i in range {
print(range.map { String(i * $0) }.joined(separator: "\t"))
}

You can store the multiplication table in a 2D array of Ints. First, you can populate the first row and first column with numbers from 1 to the size of the multiplication table. Then for each element in the remaining empty positions, you just need to multiply the first element of the same row and the first element of the same column that the element resides in.
func multiplicationTable(ofSize n:Int) -> [[Int]] {
var table = Array(repeating: Array(repeating: 0, count: n), count: n)
table[0] = Array(1...n)
for i in 1..<n {
table[i][0] = i+1
for j in 1..<n {
table[i][j] = table[i][0] * table[0][j]
}
}
return table
}
multiplicationTable(ofSize: 5).forEach { row in
print(row,"\n")
}
Output:
[1, 2, 3, 4, 5]
[2, 4, 6, 8, 10]
[3, 6, 9, 12, 15]
[4, 8, 12, 16, 20]
[5, 10, 15, 20, 25]

Related

Recursive function with loops inside

I am trying to generalize loops within a recursive function...
The basic double loop is the following function:
func multiLoops(start ix:Int, upTo n:Int) {
for i in ix...n {
for j in i+1 ... n+1 {
print("it is \(i) \(j)")
}
}
}
multiLoops(start: 3, upTo: 6)
With the following result:
it is 3 4
it is 3 5
it is 3 6
it is 3 7
it is 4 5
it is 4 6
it is 4 7
it is 5 6
it is 5 7
it is 6 7
My tentative to do the same with a recursive function is the following:
func multiLoopsRecursive(start ix:Int, upTo n:Int, loopNumber:Int){
var loopNumber = loopNumber
var previous_i = ix
func loop(start ix:Int, upTo n:Int) {
for i in ix + 1...n {
print("it is \(previous_i) \(i)")
if loopNumber > 1 {
loopNumber -= 1
previous_i = i
loop(start: previous_i+1, upTo: n+loopNumber)
}
}
}
loop(start: ix, upTo: n)
}
multiLoopsRecursive(start: 3, upTo: 6, loopNumber: 2)
With the following result ...
it is 3 4
it is 4 6
it is 4 7
it is 4 5
it is 4 6
Not really the same as the basic double loop ...
I am really blocked...
Thank you for your help...
Regards
K
Basic double loop with a print loopNumber added:
for i in ix...n {
print("it is loop 1")
for j in i+1 ... n+1 {
print("it is loop 2")
print("it is \(i) \(j)")
}
}
}
multiLoops(start: 3, upTo: 6)
Result:
it is loop 1
it is loop 2
it is 3 4
it is loop 2
it is 3 5
it is loop 2
it is 3 6
it is loop 2
it is 3 7
it is loop 1
it is loop 2
it is 4 5
it is loop 2
it is 4 6
it is loop 2
it is 4 7
it is loop 1
it is loop 2
it is 5 6
it is loop 2
it is 5 7
it is loop 1
it is loop 2
it is 6 7
Larme, Please find your code with the loopNumber added:
var loopNumber = 1
func multiLoopsRecursive(start: Int, upTo: Int) {
print("it is loop \(loopNumber)")
for i in start+1...upTo+1 {
print("it is \(start) \(i)")
}
let newStart = start + 1
if newStart < upTo+1 {
loopNumber += 1
multiLoopsRecursive(start: newStart, upTo: upTo)
}
}
print("Recursive")
multiLoopsRecursive(start: 3, upTo: 6)
Result:
Recursive
it is loop 1
it is 3 4
it is 3 5
it is 3 6
it is 3 7
it is loop 2
it is 4 5
it is 4 6
it is 4 7
it is loop 3
it is 5 6
it is 5 7
it is loop 4
it is 6 7
Thank you for your support
K
Here we are !
The trick is to know in which loop you are to adapt the different variables. I leave in the code the « print loop down and up » for more clarity, but it can be suppressed of course.
Now it works with loops in loops :-)
func loopInLoop (iStart:Int, iEnd:Int, numberOfLoops : Int) {
print("what loop is it! \(loopIndex)")
var iRank = 0
for i in iStart...(iEnd - numberOfLoops + loopIndex) {
iArray[loopIndex-1] = i
iRank += 1
if loopIndex < numberOfLoops {
print ("loop down")
loopIndex += 1
loopInLoop(iStart: iStart + iRank, iEnd: iEnd, numberOfLoops: numberOfLoops)
} else {print("iArray:\(iArray)")}
}
print ("loop up")
loopIndex -= 1
}
let iStart = 3 // initial starting index of first loop, must be <= iEnd
let iEnd = 7 // ending starting index of first loop
let numberOfLoops = 2 // number of loop to execute, must be <= (iEnd-iStart)
var iArray = [Int](repeating: 0, count: numberOfLoops) // Array of indexes
var loopIndex = 1 // initial index of the loop
loopInLoop(iStart: iStart, iEnd: iEnd, numberOfLoops : numberOfLoops)
Result:
what loop is it! 1
loop down
what loop is it! 2
iArray:[3, 4]
iArray:[3, 5]
iArray:[3, 6]
iArray:[3, 7]
loop up
loop down
what loop is it! 2
iArray:[4, 5]
iArray:[4, 6]
iArray:[4, 7]
loop up
loop down
what loop is it! 2
iArray:[5, 6]
iArray:[5, 7]
loop up
loop down
what loop is it! 2
iArray:[6, 7]
loop up
loop up

Can I remove some element from a Range in Swift?

I have a ClosedRange from 1 to 10, I wanted to know can we remove some element of it? like removing 5 and 7 from that closedRange then we should have: 1 2 3 4 6 8 9 10 instead of having 1 2 3 4 5 6 7 8 9 10
let closedRange: ClosedRange<Int> = 1...10
It ends up being an array of type [ClosedRange<Int>.Element] because once you remove elements, it's not a range any more (since by definition it doesn't include all the elements between the bounds).
From the Apple docs (https://developer.apple.com/documentation/swift/closedrange):
An interval from a lower bound up to, and including, an upper bound.
let closedRange: ClosedRange<Int> = 1...10
let closedRangeArrayWithElementsMissing = closedRange.filter { $0 != 5 && $0 != 7 }
// = [1, 2, 3, 4, 6, 8, 9, 10]
Like the other answer states, no. symmetricDifference is good for this.
([5, 7] as Set).symmetricDifference(1...10)

Minimum of two multidimensional matrices, with which matrix 'won' (contained the minimum)

I have two matrices (size 4x4) and I want to find the minimum between the two. For example:
A = [ 3, 2, 4, 5;
1, 2, 0, 6;
9, 8, 5, 4;
0, 1, 0, 3 ];
B = [ 1, 1, 6, 8;
0, 4, 6, 3;
5, 6, 7, 1;
0, 2, 3, 4 ];
Now, if I did a min(A,B) in Octave, it gives me
[ 1, 1, 4, 5;
0, 2, 0, 3;
5, 6, 5, 1;
0, 1, 0, 3 ]
Is there a way to get the matrix that 'won', by which I mean which matrix contained the minimum, in each element-wise comparison?
Like, for the first element of both matrices, matrix B won and so on.
I don't want to loop through the matrices.
You can compare A and B to find out in which matrix the minimum occurred.
With A > B, you will get a matrix containing False if the entry from A was chosen, and True if the entry from B was chosen. By adding 1 to it, you will get 1 if A was chosen and 2 if B was chosen.
>> 1 + (A > B)
ans =
2 2 1 1
2 1 1 2
2 2 1 2
1 1 1 1
Alternatively, you can concatenate A and B to form a 3-dimensional array with dimensions [4, 4, 2], where C(:, :, 1) = A and where C(:, :, 2) = B. Then you can call min on this matrix C along the third axis. When calling min on one matrix, you can get the index of the "winner" directly as a second return value:
>> C = cat(3, A, B);
>> [res, idx] = min(C, [], 3)
res =
1 1 4 5
0 2 0 3
5 6 5 1
0 1 0 3
idx =
2 2 1 1
2 1 1 2
2 2 1 2
1 1 1 1

Concatenate two arrays in MATLAB

I have a 5000x2 array as:
A = [1, 3; 2, 4; 1, 6; 2, 4; 1, 7];
I have another array of size 100x2 which looks as:
B = [1, 14; 2, 15];
How can I create a third array where I am going to use column 2 of vector B as follows to modify matrix A:
C = [1, 3, 14; 2, 4, 15; 1, 6, 14; 2, 4, 15; 1, 7, 14];
I am just trying to use column 1 of B as keys which would be same as contents of column 1 of A.
Assuming the first column on B is indices = 1 2 3 4 ..., the following should work:
A =
1 3
2 4
2 6
2 4
1 7
2 8
C(:,3) = B(A(:,1),2)
C =
1 3 14
2 4 15
2 6 15
2 4 15
1 7 14
2 8 15
or if you just want 14 15 14 15:
C = [A repmat(B(:,2),size(A,1)/size(B,1),1)]
Do the following:
A(A(:,1)== key ,3) = B(B(:,1)== key ,2);
where key takes the values of 1 and 2 (and any other possible key).
What does this line do? A(:,1)== key will be true on the rows where the first column values are equal to key, and then sets the third column of A equal to the values of B that have the same key.
You should execute this line for key=1 and key=2 in order to get what you need.

MATLAB: Finding n-th smallest element in per row

I want to find the n-th smallest element for each row in a matrix.
Example:
n = 2
M = [1, 2, 3; 4, 5, 6; 7, 8 9]
Result = [2, 5, 8]
First sort the matrix by the second dimension (i.e. sort every row in ascending order):
n = 2
M = [1, 2, 3; 4, 5, 6; 7, 8 9]
M_SORTED = sort(M,2)
M_SORTED =
1 2 3
4 5 6
7 8 9
The n-th column of the matrix will contain the result:
RESULT = M_SORTED(:, n)
RESULT =
2
5
8