Fizz-Buzz solution is not working properly in kotlin - kotlin

In the Fizz-Buzz problem, we replace a number multiple of 3 with the word fizz and a number divisible by 5 with the word buzz. If a number is divisible by both three and five, we replace it with the word"FizzBuzz." in a counting incremental loop.
But my code is not working properly. Please take a look and let me know what I am doing wrong.
for (i in 1..100){
if ( i%5 == 0 || i%3 == 0) {
println("FizzBuzz")}
else if(i%5 == 0) {
println("Buzz")}
else if(i%3 == 0){
println("Fizz")}
else {
println(i)
}
}

You are using || instead of &&.
Replace:
if (i%5 == 0 || i%3 == 0) {
println("FizzBuzz")
}
With:
if (i%5 == 0 && i%3 == 0) {
println("FizzBuzz")
}
Or with:
if (i%15 == 0) {
println("FizzBuzz")
}
The more elegant solution is:
fun fizzBuzz(currentNumber: Int) = when {
currentNumber % 15 == 0 -> "FizzBuzz"
currentNumber % 3 == 0 -> "Fizz"
currentNumber % 5 == 0 -> "Buzz"
else -> "$currentNumber"
}
for (currentNumber in 1..100) {
print(fizzBuzz(currentNumber))
}

Related

Why I'm getting 'return' expression required in a function with a block body error in Kotlin?

open class Test1 {
fun name(a: Int, b: Int): Int {
if (a % 2 == 0 && b % 2 == 0) return (a * b)
if (a % 2 == 1 && b % 2 == 1) return (a + b)
if ((a % 2 == 0).xor(b % 2 == 0)) return if (a > b) (a - b) else (b - a)
}
}
class Test2 : Test1() {
}
val obj1 = Test2()
print(obj1.name(7 , 8))
I'm trying to learn inheritance in Kotlin, but when I call name function from father class and try to print the result I get error below.
error: a return expression required in a function with a block body ('{...}') }
If the first and the second condition is false, the third one must be true so you can remove the last condition. The compiler does not seem to be able to draw this conclusion, so it suspects a case where there is no return.
fun name(a: Int, b: Int): Int {
if (a % 2 == 0 && b % 2 == 0) return (a * b)
if (a % 2 == 1 && b % 2 == 1) return (a + b)
return if (a > b) (a - b) else (b - a)
}
You can also simplify this method as follows
fun name(a: Int, b: Int): Int {
if (a % 2 != b % 2) return if (a > b) (a - b) else (b - a);
return if (a % 2 == 0) (a * b) else (a + b)
}
Your last line of the function
if ((a % 2 == 0).xor(b % 2 == 0)) return if (a > b) (a - b) else (b - a)
if you add brackets for clarity, it would look like:
if ((a % 2 == 0).xor(b % 2 == 0)) {
return if (a > b) (a - b) else (b - a)
}
So if the if test is false, the code won't run, which means you've reached the end of the function and still haven't returned something. You have to return an Int.
As already answered, in order for your code to compile your function must return an int from all execution paths, your function doesn't satisfy that condition. what happens if all the if conditions eveluate to false?
And second thing is that in kotlin return is an expression, so you can lift it out like so
fun name(a: Int, b: Int): Int {
return if (a % 2 == 0 && b % 2 == 0) { (a * b) }
else if (a % 2 == 1 && b % 2 == 1) { (a + b) }
else if ((a % 2 == 0).xor(b % 2 == 0)) { if (a > b) (a - b) else (b - a) }
else SOME_DEFAULT_INT
}

Why DOESN’T Kotlin smart cast work, even when both are `val`s

In the below code, both the variables are vals, but the smart cast doesn't work even after the null check. Why?
fun SLLNode?.sumListWith(node: SLLNode?, carry: Int = 0): SLLNode? =
when {
this == null && node == null -> if (carry == 0) null else SLLNode(carry)
this == null -> node.also { it!!.value += carry } // Smart cast doesn't work here.
node == null -> this.also { value += carry } // Works here.
else -> {
...
}
}
Smart cast is working!, just make sure that value property is var in class SLLNode:
class SLLNode(var value: Int) // Not val
fun SLLNode?.sumListWith(node: SLLNode?, carry: Int = 0): SLLNode? =
when {
this == null && node == null -> if (carry == 0) null else SLLNode(carry)
this == null -> node.also { it!!.value += carry } // Smart cast doesn't work here.
node == null -> this.also { value += carry } // Works here.
else -> {
...
}
}

Use of uninitialized value of type Any in numeric context raku

I've come across a programming question at reddit (Take a look at the link for the question)
This was one the solutions in Python:
s="112213"
k=2
result=0
for i in range(len(s)):
num_seen = 0
window = {}
for ind in range(i, len(s)):
if not s[ind] in window:
num_seen += 1
window[s[ind]] = 1
else:
window[s[ind]] += 1
if window[s[ind]] == k:
num_seen -= 1
if num_seen == 0:
result +=1
elif window[s[ind]] > k:
break
print(result)
I've tried to port this solution into Raku and here is my code:
my #s=<1 1 2 2 1 3>;
my $k=2;
my $res=0;
for ^#s {
my $seen = 0;
my %window;
for #s[$_..*] {
if $^a == %window.keys.none {
$seen++;
%window{$^a} = 1;}
else {
%window{$^a} += 1;}
if %window{$^a} == $k {
$seen--;
if $seen == 0 {
$res++;} }
elsif %window{$^a} > $k {
last;}}}
say $res;
It gives this error:
Use of an uninitialized value of type Any in a numeric context in a block at ... line 13
How to fix it?
I don't feel that's a MRE. There are too many issues with it for me to get in to. What I did instead is start from the original Python and translated that. I'll add some comments:
my \s="112213" .comb; # .comb to simulate Python string[n] indexing.
my \k=2;
my $result=0; # result is mutated so give it a sigil
for ^s -> \i { # don't use $^foo vars with for loops
my $num_seen = 0;
my \window = {}
for i..s-1 -> \ind {
if s[ind] == window.keys.none { # usefully indent code!
$num_seen += 1;
window{s[ind]} = 1
} else {
window{s[ind]} += 1
}
if window{s[ind]} == k {
$num_seen -= 1;
if $num_seen == 0 {
$result +=1
}
} elsif window{s[ind]} > k {
last
}
}
}
print($result)
displays 4.
I'm not saying that's a good solution in Raku. It's just a relatively mechanical translation. Hopefully it's helpful.
As usual, the answer by #raiph is correct. I just want to do the minimal changes to your program that get it right. In this case, it's simply adding indices to both loops to make stuff clearer. You were using the context variable $_ in the first, and $^a in the second (inner), and it was getting unnecesarily confusing.
my #s=<1 1 2 2 1 3>;
my $k=2;
my $res=0;
for ^#s -> $i {
my $seen = 0;
my %window;
for #s[$i..*] -> $c {
if $c == %window.keys.none {
$seen++;
%window{$c} = 1;
} else {
%window{$c} += 1;
}
if %window{$c} == $k {
$seen--;
if $seen == 0 {
$res++;
}
} elsif %window{$c} > $k {
last;
}
}
}
say $res;
As you see , besides trying to indent everything a bit more properly, the only additional thing is to add -> $i and -> $c so that loops are indexed, and then use them where you were using implicit variables.

How do you count the variable changing in iteration of 1's

"value" can only either be 0, 60, 120, 180, 240 or 300.
When I try to count each change that "value" has using iterations I'm not getting values of +1. It gives values which are stepping by 10000. Also I do not wish to iterate when a value is reached, I only wish to iterate when it has changed one of the 6 values.
#include <stdio.h>
int angles;
int counter[6] = {0, 60, 120, 180, 240, 300};
if (a == 1 && b == 1 && c == 0)
{
value = 0;
}
if (a == 1 && b == 0 && c == 0)
{
value = 60;
}
if (a == 1 && b == 0 && c == 1)
{
value = 120;
}
if (a == 0 && b == 0 && c == 1)
{
value = 180;
}
if (a== 0 && b == 1 && c == 1)
{
value= 240;
}
if (a == 0 && b == 1 && c == 0)
{
value = 300;
}
2**3 == 8
You are missing conditions for some of the possible combinations of values.
I would put the conditions into a function and return the desired value as soon as it has been determined because that allows to sort out the conditions. Doing that, you will inevitably notice that you do not know what to return in some cases.
Other than that, it´s not clear to me what you are trying to achieve.
Something like this:
#define ERROR -1
int get_value(int a, int b, int c)
{
if(a)
{
if(b)
{
return c ? ERROR : 0;
}
else
{
return c ? 60 : 120;
}
}
else
{
if(b)
{
return c ? 240 : 300;
}
else
{
return c ? 180 : ERROR;
}
}
return ERROR;
}
I would probably avoid all this, consider each of the three values as one bit and use bit operators to get to the desired value.

How to make only one of the variables have the value of 0?

I am trying to make it so that of the 4 variables, (squareType1, squareType2, squareType3, and squareType4) only one of them has a value of 0 but which variable it is should be random. The coding is off I know that but I just don't know how to fix it.
squareType1 = arc4random() %2;
squareType2 = arc4random() %2;
squareType3 = arc4random() %2;
squareType4 = arc4random() %2;
if (squareType2 == 0 || squareType3 == 0 || squareType4 == 0) {
squareType1 = 1;
}
if (squareType1 == 0 || squareType3 == 0 || squareType4 == 0) {
squareType2 = 1;
}
if (squareType2 == 0 || squareType1 == 0 || squareType4 == 0) {
squareType3 = 1;
}
if (squareType2 == 0 || squareType3 == 0 || squareType1 == 0) {
squareType4 = 1;
}
A simpler way to do this would be to set all 4 values to 1 initially and then randomly reset one of the variables to 0, e.g.
squareType1 = squareType2 = squareType3 = squareType4 = 1;
switch (arc4random() % 4)
{
case 0: squareType1 = 0; break;
case 1: squareType2 = 0; break;
case 2: squareType3 = 0; break;
case 3: squareType4 = 0; break;
}
Note that you will probably find life easier, in this instance and in general, if you refactor the four separate variables into a single array, e.g. int squareType[4];.