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
Related
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]
Sorry my question wasn't very clear.
I'm iterating through number ([1...50]) and the results should be like:
1 % 5 = 1
2 % 5 = 2
3 % 5 = 3
4 % 5 = 4
5 % 5 = 0 // I want this to be 5
...
10 % 5 = 0 // I want this to be 5 as well
simple code is
let number = Int.random(in: 1...5)
print(number)
or
let number = Int.random(in: 1...100)
print(number % 5 + 1)
To get the desired result after you edited the question use
(number - 1) % 5 + 1
as suggested by John Montgomery in the comments.
I have the following problem. Let's say I have four possible values {1 2 3 4} and I want a specific behavior of mod function
The behavior I seek is this one
1 mod 4 = 1
2 mod 4 = 2
3 mod 4 = 3
4 mod 4 = 4
but I have the following results with matlab.
1 mod 4 = 1
2 mod 4 = 2
3 mod 4 = 3
4 mod 4 = 0
Are there any ideas as how to achieve the desired behavior with the simplest way possible in MATLAB?
If A holds those values, you can subtract 1, perform mod and add back 1.
Sample run -
>> A = 1:8
A =
1 2 3 4 5 6 7 8
>> mod(A-1,4)+1
ans =
1 2 3 4 1 2 3 4
How about:
function [result] = my_mod(x,y)
m = mod(x,y);
result = m+~m*y;
The ~ negates the result from mod, i.e. :
~0 == 1
~1 == 0
~2 == 0
...
So we only add y if the result from mod is 0.
demo
>> my_mod(1:8, 4)
ans =
1 2 3 4 1 2 3 4
Here is a simple double array:
array=[3 1 1]
Largest element index is 1
or:
array=[3 9 1]
Largest element index is 2
How can I get the largest element index?
Use the second output argument of the max function:
[ max_value, max_index ] = max( [ 3 9 1 ] )
My standard solution is to do
index = find(array == max(array), 1);
which returns the index of the first element that is equal to the maximum value. You can fiddle with the options of find if you want the last element instead, etc.
If you need to get the max value of each row you can use:
array = [1, 2, 3; 6, 2, 1; 4, 1, 5];
[max_value max_index] = max(array, [], 2)
%3, 3
%6, 1
%5, 3
In Octave If
A =
1 3 2
6 5 4
7 9 8
1) For Each Column Max value and corresponding index of them can be found by
>> [max_values,indices] =max(A,[],1)
max_values =
7 9 8
indices =
3 3 3
2) For Each Row Max value and corresponding index of them can be found by
>> [max_values,indices] =max(A,[],2)
max_values =
3
6
9
indices =
2
1
2
Similarly For minimum value
>> [min_values,indices] =min(A,[],1)
min_values =
1 3 2
indices =
1 1 1
>> [min_values,indices] =min(A,[],2)
min_values =
1
4
7
indices =
1
3
1
I am trying to find the sum of the following matrix in matlab [1 1 1 1; 1 2 1 2; 4 5 3 2; 1 3 2 4; 10 11 1 1; 90 9 2 1]
I am trying to do so using a nested for statement yet i keep getting errors. please help
Must use nested for
My code:
A = [1 1 1 1; 1 2 1 2; 4 5 3 2; 1 3 2 4; 10 11 1 1; 90 9 2 1];
for j=1:4,
for i=1:6,
sum = A(j,:)+A(j+1,:)+A(j+2,:)
end
end
You will need to change your code from this:
A = [1 1 1 1; 1 2 1 2; 4 5 3 2; 1 3 2 4; 10 11 1 1; 90 9 2 1];
for j=1:4,
for i=j:6,
sum = A(j,:)+A(j+1,:)+A(j+2,:);
end
end
to this:
A = [1 1 1 1; 1 2 1 2; 4 5 3 2; 1 3 2 4; 10 11 1 1; 90 9 2 1];
sum = 0;
for j=1:4,
for i=1:6,
sum = sum + A(j,i);
end
end
Note various modifications:
Initialize sum=0. If you're using this in the interpreter, you'll be starting off with the previous result, guranteeing you don't get the right result.
Cumulate the values. If you assign to sum at each iteration, you'll throw away the result of other iterations.
There is no point in writing the outer loop if you're going to hardcode j+1, j+2, etc. in the inner loop.
Fix the inner loop so that it starts iterating at 1.
Suppress output in the inner loop by using a semicolon to get a clean result.
I will not post the corrected code, I'll instead add comments to the code you posted:
A = [1 1 1 1; 1 2 1 2; 4 5 3 2; 1 3 2 4; 10 11 1 1; 90 9 2 1];
% you are missing sum initialization here - you should first set sum to zero
for j=1:4, % there is no comma needed at the end
for i=j:6, % you want to iterate all the rows, from 1 to 6
sum = A(j,:)+A(j+1,:)+A(j+2,:) % you should be adding to the sum - i.e sum is sum + current field A(j, i)
end
end
Why don't you just use sum()?