swift: about ternary operator Question. Why my code is error code??? Please tell me why I'm wrong - swift

swift: about ternary operator Question. Why my code is error code??? Please tell me why I'm wrong.
var arr = [0,1,2,3,4,5,6,7,8]
var result = 0;
for a in 0..<arr.count{
for b in 1..<arr.count - 1{
for c in 2..<arr.count - 2 {
arr[a] + arr[b] + arr[c] <= input[1] ? result = arr[a] + arr[b] +arr[c] : continue
}
}
}
[this is my error]
[1]: https://i.stack.imgur.com/UdiUB.png

In Swift, the ternary condition operator is an expression which takes the form
<condition> ? <expression if true> : <expression if false>
Expressions are part of larger statements, and the ternary specifically is one which evaluates to either the expression after the ?, or the one after the : depending on the truth of the condition.
continue, however, is not an expression but a statement on its own, which means that it cannot be on either side of the ternary.
Thinking about this another way: expressions evaluate to some value (e.g., can be put on the right-hand-side of an assignment, like x = <some expression>), while statements do not (e.g., it doesn't make sense to write x = continue).
You will need to express this in the form of a regular if-statement then:
if arr[a] + arr[b] + arr[c] <= input[1] {
result = arr[a] + arr[b] +arr[c]
} else {
continue
}
Note that the above code might be grammatically correct (in that it will compile), but it is unlikely to be what you mean: the loop will automatically continue at the end of execution even if arr[a] + arr[b] + arr[c] <= input[1] by default, which means that your result may get overwritten later in the loop. It seems likely that you mean something like
outer_loop: for a in 0 ..< arr.count {
for b in 1 ..< arr.count - 1 {
for c in 2 ..< arr.count - 2 {
if arr[a] + arr[b] + arr[c] <= input[1] {
result = arr[a] + arr[b] + arr[c]
// `break` would only exit the `c` loop, but with this label
// we can exit all loops at once.
break outer_loop
}
}
}
}

Related

C question in logical OR: 2 operands evaluated (0) false, but the result works as TRUE range

My doubt is about the basic theory of "or logical operator". Especifically, logical OR returns true only if either one operand is true.
For instance, in this OR expression (x<O || x> 8) using x=5 when I evalute the 2 operand, I interpret it as both of them are false.
But I have an example that does not fit wiht it rule. On the contrary the expression works as range between 0 and 8, both included.
Following the code:
#include <stdio.h>
int main(void)
{
int x ; //This is the variable for being evaluated
do
{
printf("Imput a figure between 1 and 8 : ");
scanf("%i", &x);
}
while ( x < 1 || x > 8); // Why this expression write in this way determinate the range???
{
printf("Your imput was ::: %d ",x);
printf("\n");
}
printf("\n");
}
I have modified my first question. I really appreciate any helpo in order to clarify my doubt
In advance, thank you very much. Otto
It's not a while loop; it's a do ... while loop. The formatting makes it hard to see. Reformatted:
#include <stdio.h>
int main(void) {
int x;
// Execute the code in the `do { }` block once, no matter what.
// Keep executing it again and again, so long as the condition
// in `while ( )` is true.
do {
printf("Imput a figure between 1 and 8 : ");
scanf("%i", &x);
} while (x < 1 || x > 8);
// This creates a new scope. While perfectly valid C,
// this does absolutely nothing in this particular case here.
{
printf("Your imput was ::: %d ",x);
printf("\n");
}
printf("\n");
}
The block with the two printf calls is not part of the loop. The while (x < 1 || x > 8) makes it so that the code in the do { } block runs, so long as x < 1 or x > 8. In other words, it runs until x is between 1 and 8. This has the effect of asking the user to input a number again and again, until they finally input a number that's between 1 and 8.

Why is my code returning 0? And not the numbers of Upper and Lower characters?

I'm trying to code that calculates how many upper and lower characters in a string. Here's my code.
I've been trying to convert it to string, but not working.
def up_low(string):
result1 = 0
result2 = 0
for x in string:
if x == x.upper():
result1 + 1
elif x == x.lower():
result2 + 1
print('You have ' + str(result1) + ' upper characters and ' +
str(result2) + ' lower characters!')
up_low('Hello Mr. Rogers, how are you this fine Tuesday?')
I expect my outcome to calculate the upper and lower characters. Right now I'm getting "You have 0 upper characters and 0 lower characters!".
It's not adding up to result1 and result2.
Seems your error is in the assignation, missimg a '=' symbol (E.g. result1 += 1)
for x in string:
if x == x.upper():
result1 += 1
elif x == x.lower():
result2 +**=** 1
The problem is in the line result1 + 1 and result2 + 1. This is an expression, but not an assignment. In other words, you increment the counter, and then the incremented value goes nowhere.
The solution is to work the assignment operator = into there somewhere.

for loop over odd numbers in swift

I am trying to solve the task
Using a standard for-in loop add all odd numbers less than or equal to 100 to the oddNumbers array
I tried the following:
var oddNumbers = [Int]()
var numbt = 0
for newNumt in 0..<100 {
var newNumt = numbt + 1; numbt += 2; oddNumbers.append(newNumt)
}
print(oddNumbers)
This results in:
1,3,5,7,9,...199
My question is: Why does it print numbers above 100 although I specify the range between 0 and <100?
You're doing a mistake:
for newNumt in 0..<100 {
var newNumt = numbt + 1; numbt += 2; oddNumbers.append(newNumt)
}
The variable newNumt defined inside the loop does not affect the variable newNumt declared in the for statement. So the for loop prints out the first 100 odd numbers, not the odd numbers between 0 and 100.
If you need to use a for loop:
var odds = [Int]()
for number in 0...100 where number % 2 == 1 {
odds.append(number)
}
Alternatively:
let odds = (0...100).filter { $0 % 2 == 1 }
will filter the odd numbers from an array with items from 0 to 100. For an even better implementation use the stride operator:
let odds = Array(stride(from: 1, to: 100, by: 2))
If you want all the odd numbers between 0 and 100 you can write
let oddNums = (0...100).filter { $0 % 2 == 1 }
or
let oddNums = Array(stride(from: 1, to: 100, by: 2))
Why does it print numbers above 100 although I specify the range between 0 and <100?
Look again at your code:
for newNumt in 0..<100 {
var newNumt = numbt + 1; numbt += 2; oddNumbers.append(newNumt)
}
The newNumt used inside the loop is different from the loop variable; the var newNumt declares a new variable whose scope is the body of the loop, so it gets created and destroyed each time through the loop. Meanwhile, numbt is declared outside the loop, so it keeps being incremented by 2 each time through the loop.
I see that this is an old question, but none of the answers specifically address looping over odd numbers, so I'll add another. The stride() function that Luca Angeletti pointed to is the right way to go, but you can use it directly in a for loop like this:
for oddNumber in stride(from:1, to:100, by:2) {
// your code here
}
stride(from:,to:,by:) creates a list of any strideable type up to but not including the from: parameter, in increments of the by: parameter, so in this case oddNumber starts at 1 and includes 3, 5, 7, 9...99. If you want to include the upper limit, there's a stride(from:,through:,by:) form where the through: parameter is included.
If you want all the odd numbers between 0 and 100 you can write
for i in 1...100 {
if i % 2 == 1 {
continue
}
print(i - 1)
}
For Swift 4.2
extension Collection {
func everyOther(_ body: (Element) -> Void) {
let start = self.startIndex
let end = self.endIndex
var iter = start
while iter != end {
body(self[iter])
let next = index(after: iter)
if next == end { break }
iter = index(after: next)
}
}
}
And then you can use it like this:
class OddsEvent: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
(1...900000).everyOther{ print($0) } //Even
(0...100000).everyOther{ print($0) } //Odds
}
}
This is more efficient than:
let oddNums = (0...100).filter { $0 % 2 == 1 } or
let oddNums = Array(stride(from: 1, to: 100, by: 2))
because supports larger Collections
Source: https://developer.apple.com/videos/play/wwdc2018/229/

I got error message about simulink "Output argument is not assigned on some execution paths"

In simulink, I made some model using "MATLAB function"block
but I met error message here.
here is code and error message.
function [VTAS,postVTAS]=fcn(mode,initialVTAS,a,t,preVTAS)
if mode == 1
VTAS = initialVTAS + (a * t) ;
postVTAS = VTAS;
elseif mode == 2
datasize = length(preVTAS);
lastvalue = preVTAS(datasize);
VTAS = lastvalue + 0;
postVTAS = VTAS;
end
end
Output argument 'VTAS' is not assigned on some execution paths.
Function 'MATLAB Function' (#36.25.28), line 1, column 26:
"fcn"
Launch diagnostic report.
I think there is no problem about output "VTAS"
please teach me what is a problems.
As the compiler tells you, under some circumstances there is no output value assigned to VTAS. The reason is that you only assign values to that output if mode is 1 or 2. The compiler doesn't know what values are feasible for mode. To remedy this, you need to make sure that VTAS is assigned under any and all circumstances.
This could be accomplished by, e.g. adding an else construct, like so:
function [VTAS,postVTAS]=fcn(mode,initialVTAS,a,t,preVTAS)
if mode == 1
VTAS = initialVTAS + (a * t) ;
postVTAS = VTAS;
elseif mode == 2
datasize = length(preVTAS);
lastvalue = preVTAS(datasize);
VTAS = lastvalue + 0;
postVTAS = VTAS;
else
VTAS = NaN;
postVTAS = NaN;
end
end
Edit:
Additionally, it would be good practice for the else case to throw an error. This would be helpful for debugging.
As a minor note, for every case, postVTAS is equal to VTAS, so essentially it is superfluous to return both from the function.

Reducing the number of brackets in Swift

Does anyone know if there is a way to use some kind shorthand in swift? more specifically, leaving out the braces in things like IF statements... eg
if num == 0
// Do something
instead of
if num == 0
{
// Do something
}
Those braces become rather space consuming when you have a few nested IF's.
PS. I do know I can do the following:
if num == 0 {
// Do something }
But I'm still curious if that sort of thing is possible
You can do that :
let x = 10, y = 20;
let max = (x < y) ? y : x ; // So max = 20
And so much interesting things :
let max = (x < y) ? "y is greater than x" : "x is greater than y" // max = "y is greater than x"
let max = (x < y) ? true : false // max = true
let max = (x > y) ? func() : anotherFunc() // max = anotherFunc()
(x < y) ? func() : anotherFunc() // code is running func()
This following stack : http://codereview.stackexchange.com can be better for your question ;)
Edit : ternary operators and compilation
By doing nothing more than replacing the ternary operator with an if else statement, the build time was reduced by 92.9%.
https://medium.com/#RobertGummesson/regarding-swift-build-time-optimizations-fc92cdd91e31#.42uncapwc
In swift you have to add braces even if there is just one statement in if:
if num == 0 {
// Do something
}
You cannot leave the braces, that how swift if statement work.
You could use a shorthand if statement like you would in objective-c:
num1 < num2 ? DO SOMETHING IF TRUE : DO SOMETHING IF FALSE
Swift 2.0 update
Method 1:
a != nil ? a! : b
Method 2: Shorthand if
b = a ?? ""
Referance: Apple Docs: Ternary Conditional Operator
and it does work,
u.dob = (userInfo["dob"] as? String) != nil ? (userInfo["dob"] as! String):""
I am replacing a json string with blank string if it is nil.
Edit: Adding Gerardo Medina`s suggestion...we can always use shorthand If
u.dob = userInfo["dob"] as? String ?? ""
It is called shorthand if-else condition. If you are into iOS development in Swift, then you can also manipulate your UI objects' behaviour with this property.
For e.g. - I want my button to be enabled only when there is some text in the textfield. In other words, should stay disabled when character count in textfield is zero.
button.enabled = (textField.characters.count > 0) ? true : false
its very simple :
in Swift 4
playButton.currentTitle == "Play" ? startPlay() : stopPlay()
Original Code is
if playButton.currentTitle == "Play"{
StartPlay()
}else{
StopPlay()
}
You could always put the entire if on one line:
if num == 0 { temp = 0 }