C# return and display syntax issue - c#

I am having trouble passing the return value from TheMethod() to Main and displaying the word if the if statement is passed as true.
I have thought of two ways of doing this, neither has worked but I think I am missing synatx.
Using a return ?; non void method and then displaying the returned value.
Using a void method and actually writing out(example below)
So yes I am new at this, however I have made so many iterations everything is blending together and I have forgot what I have tried. Any help on the syntax be great for either of these ways.
Basically I need it to iterate numbers
1,2,3,4 and depending on if the current iteration matches an expression in the if statements it will display a word.
Example:
if (3 = i)
{
Console.WriteLine("Word");
}
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Proj5
{
class Program
{
int i = 0;
static void Main(int i)
{
for (i = 0; i < 101; i++)
{
Console.WriteLine("test");
}
}
string TheMethod(int i)
{
string f = "Word1";
string b = "Word2";
if (i == 3)
{
return f;
}
if (i == 5)
{
return b;
}
if (0 == (i % 3))
{
return f;
}
if (0 == i % 5)
{
return b;
}
else
{
return b;
}
}
}
}

Note: You don't need if i == 5 and a separate one for i % 5 == 0. % is "mod" which means the remainder after the division, so 5 / 5 = 1, there is no remainder so 5 mod 5 = 0...
Here is a rough guide/fix for you attempt at FizzBuzz:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Proj5
{
class Program
{
private static void Main()
{
for (int i = 0; i < 101; i++)
{
Console.WriteLine(TheMethod(i));
}
}
string TheMethod(int i)
{
string f = "Fizz";
string b = "Buzz";
if ((i % 3 == 0) && (i % 5 == 0))
{
return f+b;
}
if (i % 3 == 0)
{
return f;
}
if (i % 5 == 0)
{
return b;
}
return i.ToString();
}
}
}
However there are cleaner solutions:
string result = "";
for (int i = 1; i < = 101; ++i)
{
if ((i % 3 == 0) && (i % 5 == 0)) result += "FizzBuzz";
else if (i % 3 == 0) result += "Fizz";
else if (i % 5 == 0) result += "Buzz";
else result += i.ToString();
result += ", ";
}
Or, if you prefer LINQ-y Lambas:
public static void FizzBuzz()
{
Dictionary<Func<int, bool>, Func<int, string>> rules = new Dictionary<Func<int, bool>, Func<int, string>>();
rules.Add(x => x % 5 == 0 && x % 3 == 0, x => “fizzbuzz”);
rules.Add(x => x % 3 == 0, x => "fizz");
rules.Add(x => x % 5 == 0, x => "buzz");
rules.Add(x => x % 5 != 0 && x % 3 != 0, x => x.ToString());
rules.Add(x => true, x => "\n");
var output = from n in Enumerable.Range(1, 100)
from f in rules
where f.Key(n)
select f.Value(n);
output.ToList().ForEach(x => Console.Write(x));
}

You can't refer to non-static variables (i) and methods (TheMethod) from inside your static Main class. Try this:
class Program
{
static void Main()
{
for (int i = 0; i < 101; i++)
{
Console.WriteLine(TheMethod(i));
}
}
static string TheMethod(int i)
{
string f = "Word1";
string b = "Word2";
if (i%3 == 0) return f;
if (i%5 == 0) return b;
return b;
}
}

Related

Return value only of last iteration

I am trying to calculate the Greatest Common Divisor using a while loop. I am therefore looking for the greatest number (i.e. the last value of the loop). How do I get rid of the preceding numbers?
Example:
The greatest common divisor of 84 and 18 is 6. However, my code gives me the numbers 2, 3, and 6. What do I need to change to get only the last number?
using System;
namespace CalculateGCD
{
class Program
{
static void Main(string[] args)
{
int a = int.Parse(Console.ReadLine());
int b = int.Parse(Console.ReadLine());
int i = 1;
while (i <= Math.Min(a, b))
{
i++;
if (a % i == 0 && b % i == 0)
{
Console.WriteLine("GCD:{0}", i);
}
}
}
}
}
Define a variable called max then print the max out of the while loop like this:
int max = 0;
while (i <= Math.Min(a, b))
{
i++;
if (a % i == 0 && b % i == 0)
{
max = i;
}
}
Console.WriteLine("GCD:{0}", max);
Also if you are using C# 6 you could simplify your Console.WriteLine by using string interpolation like this:
Console.WriteLine($"GCD:{max}");
There is a simple solution which will calculate GCD
static int GCD(int a, int b) {
return b == 0 ? a : GCD(b, a % b);
}
and you can use it like below
using System;
namespace CalculateGCD
{
public class Program
{
public static void Main(string[] args)
{
int a = int.Parse(Console.ReadLine());
int b = int.Parse(Console.ReadLine());
Console.WriteLine(GCD(a,b));
}
static int GCD(int a, int b)
{
return b == 0 ? a : GCD(b, a % b);
}
}
}
You can invert the loop, insted of going from 1 to the Min between a and b, search from the Min to 1.
int i = Math.Min(a, b);
while (i > 0)
{
i--;
if (a % i == 0 && b % i == 0)
{
Console.WriteLine("GCD:{0}", i);
break;
}
}
simply reverse the enumeration sequence will do
int a = int.Parse(Console.ReadLine());
int b = int.Parse(Console.ReadLine());
int i = Math.Min(a ,b);
while (i > 1)
{
if (a % i == 0 && b % i == 0)
{
Console.WriteLine("GCD:{0}", i);
break;//greatest will be the first
}
i--;
}
int gcd;
while (i <= Math.Min(a, b))
{
i++;
if (a % i == 0 && b % i == 0)
{
gcd=i;
}
}
Console.WriteLine("GCD:{0}",gcd);
Save greatest common divisor in a variable.

Convert loop logic to LINQ

Does anyone know if there's a cleaner way of doing this (maybe LINQ)? I want to group the value into bucket, and give it a score, so for example in the code below, if the value is:
less or equal to 5, increase the score by 1
10 and below, increase score by 2
15 and below, increase score by 3
else increase by 4.
There are about 10 properties that I have to do this for, and each property have different range for scoring.
public static PScore GetScore(IEnumerable<PStat> rs)
{
var data = new PScore();
foreach(var item in rs)
{
if(item.Kill <= 5)
{
data.Kills++;
}
else if (item.Kill <= 10)
{
data.Kills += 2;
}
else if (item.Kill <= 15)
{
data.Kills += 3;
}
else
{
data.Kills += 4;
}
}
return data;
}
edit#1
Thanks everyone, the ranges varied as well, and I have 10 properties to loop through, so I use this and just passed in the value and ranges
public static int GetScoreASC(int value, int[] range)
{
if (value <= range[0])
{
return 1;
}
else if (value <= range[1])
{
return 2;
}
else if (value <= range[2])
{
return 3;
}
else if (value <= range[3])
{
return 4;
}
else if (value <= range[4])
{
return 5;
}
else if (value <= range[5])
{
return 6;
}
else if (value <= range[6])
{
return 7;
}
else if (value <= range[7])
{
return 8;
}
else if (value <= range[8])
{
return 9;
}
else
{
return 10;
}
}
This way I can reused the same method for all properties.
I would do some math per each property using LINQ:
public static PScore GetScore(IEnumerable<PStat> rs)
{
var data = new PScore();
data.Kills = rs.Sum(item => Math.Min(item.Kill / 5 + (item.Kill % 5 == 0 ? 0 : 1), 4));
return data;
}
You can repeat yourself less by using Select to grab the Kill values from rs and then Sum to aggregate across them.
public static PScore GetScore(IEnumerable<PStat> rs)
{
return new PScore
{
Kills = rs.Select(item => item.Kill).Sum(kill =>
{
if (kill <= 5) return 1;
if (kill <= 10) return 2;
if (kill <= 15) return 3;
return 4;
})
};
}
If you like Konrad's style of converting the conditionals to a closed form computation, you need to correct his formula slightly. I personally would stick with the conditionals for this, though.
public static PScore GetScore(IEnumerable<PStat> rs)
{
return new PScore
{
Kills = rs.Select(item => item.Kill)
.Sum(kill => Math.Max(1, Math.Min((kill + 4) / 5, 4)));
};
}

Print the prime numbers from 0 to 10,000

Im currently trying to create a program that prints the prime numbers from 0 to 10,000 using only for,do while and ifs. I created this program but it doesn't runs
static void Main(string[] args)
{
for (int x = 2; x < 10000; x++)
{
for (int y = 1; y < x; y++)
{
if (x % y != 0)
{
Console.WriteLine(x);
}
}
Console.ReadKey();
}
I don't know where the problem is and also if the for inside resets.
Try this with no bool variable!!!:
static void Main(string[] args)
{
for (int x = 2; x < 10000; x++)
{
int isPrime = 0;
for (int y = 1; y < x; y++)
{
if (x % y == 0)
isPrime++;
if(isPrime == 2) break;
}
if(isPrime != 2)
Console.WriteLine(x);
isPrime = 0;
}
Console.ReadKey();
}
Check Console.ReadKey(); it should be after upper for loop, you can even change condition for upper for loot with <= since 10000 also need to check for prime condition.
Below is the efficient way to print prime numbers between 0 and 10000
using System.IO;
using System;
class Program
{
static void Main()
{
Console.WriteLine("Below are prime numbers between 0 and 10000!");
Console.WriteLine(2);
for(int i=3;i<=10000;i++)
{
bool isPrime=true;
for(int j=2;j<=Math.Sqrt(i);j++)
{
if(i%j==0)
{
isPrime=false;
break;
}
}
if(isPrime)
{
Console.WriteLine(i);
}
}
}
}
Is there any reason that you put Console.ReadKey(); inside of loop?
You should put that out of the loop unless press key during loop.
static void Main(string[] args)
{
for (int x = 2; x < 10000; x++)
{
for (int y = 1; y < x; y++)
{
if (x % y != 0)
{
Console.WriteLine(x);
}
}
}
Console.ReadKey();
}
And probably that code is just print lots of x.
You should to fix it.
The first problem is that x % 1 will always be zero, at least for non-zero x. You need to start the test (inner) loop at one and, for efficiency, stop when you've exceeded the square root of the number itself - if n has a factor f where f > sqrt(n), you would have already found the factor n / f.
The second problem is that you will write out a candidate number every time the remainder is non-zero. So, because 15 % 4 is three, it will be output despite the fact that fifteen is very much a non-prime. It will also be output at 15 % 2, 15 % 4, 15 % 6, 15 % 7, and so on.
The normal (naive) algorithm for prime testing is:
# All numbers to test.
foreach number 2..whatever:
# Assume prime, check all numbers up to squareroot(number).
isPrime = true
foreach test 2..infinity until test * test > number:
# If a multiple, flag as composite and stop inner loop.
if number % test == 0:
isPrime = false
exit foreach
end
end
# If never flagged as composite, output as prime.
if isPrime:
output number
end
Here is simple logic to Print Prime No for any upper limit.
Input : 10 Output : 2 , 3 , 5 ,7
namespace PurushLogics
{
class Purush_PrimeNos
{
static void Main()
{
//Prime No Program
bool isPrime = true;
Console.WriteLine("Enter till which number you would like print Prime Nos\n");
int n = int.Parse(Console.ReadLine());
Console.WriteLine("Prime Numbers : ");
for (int i = 2; i <= n; i++)
{
for (int j = 2; j <= n; j++)
{
if (i != j && i % j == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
{
Console.Write("\t" + i);
}
isPrime = true;
}
Console.ReadKey();
}
}
}
Here is my code where you can generate and print the prime numbers between two numbers (in between string_starting_number and string_last_number). The lowest possible value for string_starting_number is 0 and the highest possible value for string_last_number is decimal.MaxValue-1=79228162514264337593543950334 and not 79228162514264337593543950335 because of the decimal_a++ command inside a for loop which will result to an overflow error.
Take note that you should input the values in string type in string_starting_number and in string_last_number.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GeneratingPrimeNumbers
{
class Program
{
static void Main(string[] args)
{
string string_starting_number = "1"; //input here your choice of starting number
string string_last_number = "10"; //input here your choice of last number
decimal decimal_starting_number = Convert.ToDecimal(string_starting_number);
decimal decimal_last_number = Convert.ToDecimal(string_last_number);
string primenumbers = "";
ulong ulong_b;
ulong ulong_c;
if (decimal_starting_number <= ulong.MaxValue)
{
ulong ulong_starting_number = Convert.ToUInt64(decimal_starting_number);
ulong ulong_last_number;
if (decimal_last_number > ulong.MaxValue)
{
ulong_last_number = ulong.MaxValue;
}
else
{
ulong_last_number = Convert.ToUInt64(decimal_last_number);
}
if (ulong_starting_number == 0 || ulong_starting_number == 1 || ulong_starting_number == 2 || ulong_starting_number == 3)
{
primenumbers = 2 + " " + 3;
ulong_starting_number = 5;
}
if (ulong_starting_number % 2 == 0)
{
ulong_starting_number++;
}
ulong ulong_a;
for (ulong_a = ulong_starting_number; ulong_a <= ulong_last_number; ulong_a += 2)
{
ulong_b = Convert.ToUInt64(Math.Ceiling(Math.Sqrt(ulong_a)));
for (ulong_c = 3; ulong_c <= ulong_b; ulong_c += 2)
{
if (ulong_a % ulong_c == 0)
{
goto next_value_of_ulong_a;
}
}
primenumbers = primenumbers + " " + ulong_a;
next_value_of_ulong_a:
{
}
}
}
if (decimal_last_number > ulong.MaxValue)
{
string ulong_maximum_value_plus_two = "18446744073709551617";
if (decimal_starting_number <= ulong.MaxValue)
{
decimal_starting_number = Convert.ToDecimal(ulong_maximum_value_plus_two);
}
if (decimal_starting_number % 2 == 0)
{
decimal_starting_number++;
}
decimal decimal_a;
for (decimal_a = decimal_starting_number; decimal_a <= decimal_last_number; decimal_a += 2)
{
ulong_b = Convert.ToUInt64(Math.Ceiling(Math.Sqrt(ulong.MaxValue) * Math.Sqrt(Convert.ToDouble(decimal_a / ulong.MaxValue))));
for (ulong_c = 3; ulong_c <= ulong_b; ulong_c += 2)
{
if (decimal_a % ulong_c == 0)
{
goto next_value_of_decimal_a;
}
}
primenumbers = primenumbers + " " + decimal_a;
next_value_of_decimal_a:
{
}
}
}
Console.WriteLine(primenumbers);
Console.ReadKey();
}
}
}

Find the missing integer in Codility

I need to "Find the minimal positive integer not occurring in a given sequence. "
A[0] = 1
A[1] = 3
A[2] = 6
A[3] = 4
A[4] = 1
A[5] = 2, the function should return 5.
Assume that:
N is an integer within the range [1..100,000];
each element of array A is an integer within the range [−2,147,483,648..2,147,483,647].
I wrote the code in codility, but for many cases it did not worked and the performance test gives 0 %. Please help me out, where I am wrong.
class Solution {
public int solution(int[] A) {
if(A.Length ==0) return -1;
int value = A[0];
int min = A.Min();
int max = A.Max();
for (int j = min+1; j < max; j++)
{
if (!A.Contains(j))
{
value = j;
if(value > 0)
{
break;
}
}
}
if(value > 0)
{
return value;
}
else return 1;
}
}
The codility gives error with all except the example, positive and negative only values.
Edit: Added detail to answer your actual question more directly.
"Please help me out, where I am wrong."
In terms of correctness: Consider A = {7,2,5,6,3}. The correct output, given the contents of A, is 1, but our algorithm would fail to detect this since A.Min() would return 2 and we would start looping from 3 onward. In this case, we would return 4 instead; since it's the next missing value.
Same goes for something like A = {14,15,13}. The minimal missing positive integer here is again 1 and, since all the values from 13-15 are present, the value variable will retain its initial value of value=A[0] which would be 14.
In terms of performance: Consider what A.Min(), A.Max() and A.Contains() are doing behind the scenes; each one of these is looping through A in its entirety and in the case of Contains, we are calling it repeatedly for every value between the Min() and the lowest positive integer we can find. This will take us far beyond the specified O(N) performance that Codility is looking for.
By contrast, here's the simplest version I can think of that should score 100% on Codility. Notice that we only loop through A once and that we take advantage of a Dictionary which lets us use ContainsKey; a much faster method that does not require looping through the whole collection to find a value.
using System;
using System.Collections.Generic;
class Solution {
public int solution(int[] A) {
// the minimum possible answer is 1
int result = 1;
// let's keep track of what we find
Dictionary<int,bool> found = new Dictionary<int,bool>();
// loop through the given array
for(int i=0;i<A.Length;i++) {
// if we have a positive integer that we haven't found before
if(A[i] > 0 && !found.ContainsKey(A[i])) {
// record the fact that we found it
found.Add(A[i], true);
}
}
// crawl through what we found starting at 1
while(found.ContainsKey(result)) {
// look for the next number
result++;
}
// return the smallest positive number that we couldn't find.
return result;
}
}
The simplest solution that scored perfect score was:
public int solution(int[] A)
{
int flag = 1;
A = A.OrderBy(x => x).ToArray();
for (int i = 0; i < A.Length; i++)
{
if (A[i] <= 0)
continue;
else if (A[i] == flag)
{
flag++;
}
}
return flag;
}
Fastest C# solution so far for [-1,000,000...1,000,000].
public int solution(int[] array)
{
HashSet<int> found = new HashSet<int>();
for (int i = 0; i < array.Length; i++)
{
if (array[i] > 0)
{
found.Add(array[i]);
}
}
int result = 1;
while (found.Contains(result))
{
result++;
}
return result;
}
A tiny version of another 100% with C#
using System.Linq;
class Solution
{
public int solution(int[] A)
{
// write your code in C# 6.0 with .NET 4.5 (Mono)
var i = 0;
return A.Where(a => a > 0).Distinct().OrderBy(a => a).Any(a => a != (i = i + 1)) ? i : i + 1;
}
}
A simple solution that scored 100% with C#
int Solution(int[] A)
{
var A2 = Enumerable.Range(1, A.Length + 1);
return A2.Except(A).First();
}
public class Solution {
public int solution( int[] A ) {
return Arrays.stream( A )
.filter( n -> n > 0 )
.sorted()
.reduce( 0, ( a, b ) -> ( ( b - a ) > 1 ) ? a : b ) + 1;
}
}
It seemed easiest to just filter out the negative numbers. Then sort the stream. And then reduce it to come to an answer. It's a bit of a functional approach, but it got a 100/100 test score.
Got an 100% score with this solution:
https://app.codility.com/demo/results/trainingUFKJSB-T8P/
public int MissingInteger(int[] A)
{
A = A.Where(a => a > 0).Distinct().OrderBy(c => c).ToArray();
if (A.Length== 0)
{
return 1;
}
for (int i = 0; i < A.Length; i++)
{
//Console.WriteLine(i + "=>" + A[i]);
if (i + 1 != A[i])
{
return i + 1;
}
}
return A.Max() + 1;
}
JavaScript solution using Hash Table with O(n) time complexity.
function solution(A) {
let hashTable = {}
for (let item of A) {
hashTable[item] = true
}
let answer = 1
while(true) {
if(!hashTable[answer]) {
return answer
}
answer++
}
}
The Simplest solution for C# would be:
int value = 1;
int min = A.Min();
int max = A.Max();
if (A.Length == 0) return value = 1;
if (min < 0 && max < 0) return value = 1;
List<int> range = Enumerable.Range(1, max).ToList();
List<int> current = A.ToList();
List<int> valid = range.Except(current).ToList();
if (valid.Count() == 0)
{
max++;
return value = max;
}
else
{
return value = valid.Min();
}
Considering that the array should start from 1 or if it needs to start from the minimum value than the Enumerable.range should start from Min
MissingInteger solution in C
int solution(int A[], int N) {
int i=0,r[N];
memset(r,0,(sizeof(r)));
for(i=0;i<N;i++)
{
if(( A[i] > 0) && (A[i] <= N)) r[A[i]-1]=A[i];
}
for(i=0;i<N;i++)
{
if( r[i] != (i+1)) return (i+1);
}
return (N+1);
}
My solution for it:
public static int solution()
{
var A = new[] { -1000000, 1000000 }; // You can try with different integers
A = A.OrderBy(i => i).ToArray(); // We sort the array first
if (A.Length == 1) // if there is only one item in the array
{
if (A[0]<0 || A[0] > 1)
return 1;
if (A[0] == 1)
return 2;
}
else // if there are more than one item in the array
{
for (var i = 0; i < A.Length - 1; i++)
{
if (A[i] >= 1000000) continue; // if it's bigger than 1M
if (A[i] < 0 || (A[i] + 1) >= (A[i + 1])) continue; //if it's smaller than 0, if the next integer is bigger or equal to next integer in the sequence continue searching.
if (1 < A[0]) return 1;
return A[i] + 1;
}
}
if (1 < A[0] || A[A.Length - 1] + 1 == 0 || A[A.Length - 1] + 1 > 1000000)
return 1;
return A[A.Length-1] +1;
}
class Solution {
public int solution(int[] A) {
int size=A.length;
int small,big,temp;
for (int i=0;i<size;i++){
for(int j=0;j<size;j++){
if(A[i]<A[j]){
temp=A[j];
A[j]=A[i];
A[i]=temp;
}
}
}
int z=1;
for(int i=0;i<size;i++){
if(z==A[i]){
z++;
}
//System.out.println(a[i]);
}
return z;
}
enter code here
}
In C# you can solve the problem by making use of built in library functions. How ever the performance is low for very large integers
public int solution(int[] A)
{
var numbers = Enumerable.Range(1, Math.Abs(A.Max())+1).ToArray();
return numbers.Except(A).ToArray()[0];
}
Let me know if you find a better solution performance wise
C# - MissingInteger
Find the smallest missing integer between 1 - 1000.000.
Assumptions of the OP take place
TaskScore/Correctness/Performance: 100%
using System;
using System.Linq;
namespace TestConsole
{
class Program
{
static void Main(string[] args)
{
var A = new int[] { -122, -5, 1, 2, 3, 4, 5, 6, 7 }; // 8
var B = new int[] { 1, 3, 6, 4, 1, 2 }; // 5
var C = new int[] { -1, -3 }; // 1
var D = new int[] { -3 }; // 1
var E = new int[] { 1 }; // 2
var F = new int[] { 1000000 }; // 1
var x = new int[][] { A, B, C, D, E, F };
x.ToList().ForEach((arr) =>
{
var s = new Solution();
Console.WriteLine(s.solution(arr));
});
Console.ReadLine();
}
}
// ANSWER/SOLUTION
class Solution
{
public int solution(int[] A)
{
// clean up array for negatives and duplicates, do sort
A = A.Where(entry => entry > 0).Distinct().OrderBy(it => it).ToArray();
int lowest = 1, aLength = A.Length, highestIndex = aLength - 1;
for (int i = 0; i < aLength; i++)
{
var currInt = A[i];
if (currInt > lowest) return lowest;
if (i == highestIndex) return ++lowest;
lowest++;
}
return 1;
}
}
}
Got 100% - C# Efficient Solution
public int solution (int [] A){
int len = A.Length;
HashSet<int> realSet = new HashSet<int>();
HashSet<int> perfectSet = new HashSet<int>();
int i = 0;
while ( i < len)
{
realSet.Add(A[i]); //convert array to set to get rid of duplicates, order int's
perfectSet.Add(i + 1); //create perfect set so can find missing int
i++;
}
perfectSet.Add(i + 1);
if (realSet.All(item => item < 0))
return 1;
int notContains =
perfectSet.Except(realSet).Where(item=>item!=0).FirstOrDefault();
return notContains;
}
class Solution {
public int solution(int[] a) {
int smallestPositive = 1;
while(a.Contains(smallestPositive)) {
smallestPositive++;
}
return smallestPositive;
}
}
Well, this is a new winner now. At least on C# and my laptop. It's 1.5-2 times faster than the previous champion and 3-10 times faster, than most of the other solutions. The feature (or a bug?) of this solution is that it uses only basic data types. Also 100/100 on Codility.
public int Solution(int[] A)
{
bool[] B = new bool[(A.Length + 1)];
for (int i = 0; i < A.Length; i++)
{
if ((A[i] > 0) && (A[i] <= A.Length))
B[A[i]] = true;
}
for (int i = 1; i < B.Length; i++)
{
if (!B[i])
return i;
}
return A.Length + 1;
}
Simple C++ solution. No additional memory need, time execution order O(N*log(N)):
int solution(vector<int> &A) {
sort (A.begin(), A.end());
int prev = 0; // the biggest integer greater than 0 found until now
for( auto it = std::begin(A); it != std::end(A); it++ ) {
if( *it > prev+1 ) break;// gap found
if( *it > 0 ) prev = *it; // ignore integers smaller than 1
}
return prev+1;
}
int[] A = {1, 3, 6, 4, 1, 2};
Set<Integer> integers = new TreeSet<>();
for (int i = 0; i < A.length; i++) {
if (A[i] > 0) {
integers.add(A[i]);
}
}
Integer[] arr = integers.toArray(new Integer[0]);
final int[] result = {Integer.MAX_VALUE};
final int[] prev = {0};
final int[] curr2 = {1};
integers.stream().forEach(integer -> {
if (prev[0] + curr2[0] == integer) {
prev[0] = integer;
} else {
result[0] = prev[0] + curr2[0];
}
});
if (Integer.MAX_VALUE == result[0]) result[0] = arr[arr.length-1] + 1;
System.out.println(result[0]);
I was surprised but this was a good lesson. LINQ IS SLOW. my answer below got me 11%
public int solution (int [] A){
if (Array.FindAll(A, x => x >= 0).Length == 0) {
return 1;
} else {
var lowestValue = A.Where(x => Array.IndexOf(A, (x+1)) == -1).Min();
return lowestValue + 1;
}
}
I think I kinda look at this a bit differently but gets a 100% evaluation. Also, I used no library:
public static int Solution(int[] A)
{
var arrPos = new int[1_000_001];
for (int i = 0; i < A.Length; i++)
{
if (A[i] >= 0)
arrPos[A[i]] = 1;
}
for (int i = 1; i < arrPos.Length; i++)
{
if (arrPos[i] == 0)
return i;
}
return 1;
}
public int solution(int[] A) {
// write your code in Java SE 8
Set<Integer> elements = new TreeSet<Integer>();
long lookFor = 1;
for (int i = 0; i < A.length; i++) {
elements.add(A[i]);
}
for (Integer integer : elements) {
if (integer == lookFor)
lookFor += 1;
}
return (int) lookFor;
}
I tried to use recursion in C# instead of sorting, because I thought it would show more coding skill to do it that way, but on the scaling tests it didn't preform well on large performance tests. Suppose it's best to just do the easy way.
class Solution {
public int lowest=1;
public int solution(int[] A) {
// write your code in C# 6.0 with .NET 4.5 (Mono)
if (A.Length < 1)
return 1;
for (int i=0; i < A.Length; i++){
if (A[i]==lowest){
lowest++;
solution(A);
}
}
return lowest;
}
}
Here is my solution in javascript
function solution(A) {
// write your code in JavaScript (Node.js 8.9.4)
let result = 1;
let haveFound = {}
let len = A.length
for (let i=0;i<len;i++) {
haveFound[`${A[i]}`] = true
}
while(haveFound[`${result}`]) {
result++
}
return result
}
class Solution {
public int solution(int[] A) {
var sortedList = A.Where(x => x > 0).Distinct().OrderBy(x => x).ToArray();
var output = 1;
for (int i = 0; i < sortedList.Length; i++)
{
if (sortedList[i] != output)
{
return output;
}
output++;
}
return output;
}
}
You should just use a HashSet as its look up time is also constant instead of a dictionary. The code is less and cleaner.
public int solution (int [] A){
int answer = 1;
var set = new HashSet<int>(A);
while (set.Contains(answer)){
answer++;
}
return answer;
}
This snippet should work correctly.
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
int result = 1;
List<int> lst = new List<int>();
lst.Add(1);
lst.Add(2);
lst.Add(3);
lst.Add(18);
lst.Add(4);
lst.Add(1000);
lst.Add(-1);
lst.Add(-1000);
lst.Sort();
foreach(int curVal in lst)
{
if(curVal <=0)
result=1;
else if(!lst.Contains(curVal+1))
{
result = curVal + 1 ;
}
Console.WriteLine(result);
}
}
}

Writing FizzBuzz

Reading the coding horror, I just came across the FizzBuzz another time.
The original post is here: Coding Horror: Why Can't Programmers.. Program?
For those who do not know:
FizzBuzz is a quite popular children's game. Counting from 1 to 100,
and every time a number is divisible by 3 the string "Fizz" is called, every time
a number is divisible by 5 the string "Buzz" is called and every time a number
is divisible by 3 and 5 both strings together "FizzBuzz" are called instead of the number.
This time, I wrote the code and it took me a minute,
but there are several things that I do not like.
Here is my code:
public void DoFizzBuzz()
{
var combinations = new Tuple<int, string>[]
{
new Tuple<int, string> (3, "Fizz"),
new Tuple<int, string> (5, "Buzz"),
};
for (int i = 1; i <= 100; ++i)
{
bool found = false;
foreach (var comb in combinations)
{
if (i % comb.Item1 == 0)
{
found = true;
Console.Write(comb.Item2);
}
}
if (!found)
{
Console.Write(i);
}
Console.Write(Environment.NewLine);
}
}
So my questions are:
How do I get rid of the bool found?
Is there a better way of testing
than the foreach?
I think your implementation is unnecessarily complex. This one does the job and is easier to understand:
public void DoFizzBuzz()
{
for (int i = 1; i <= 100; i++)
{
bool fizz = i % 3 == 0;
bool buzz = i % 5 == 0;
if (fizz && buzz)
Console.WriteLine ("FizzBuzz");
else if (fizz)
Console.WriteLine ("Fizz");
else if (buzz)
Console.WriteLine ("Buzz");
else
Console.WriteLine (i);
}
}
Unrolled for maximum efficiency. This program can outfizzbuzz all others.
public void FizzBuzz()
{
const string FIZZ = "Fizz";
const string BUZZ = "Buzz";
const string FIZZBUZZ = "FizzBuzz";
int i = 0;
while (i < 150)
{
Console.WriteLine(++i);
Console.WriteLine(++i);
Console.WriteLine(FIZZ); ++i;
Console.WriteLine(++i);
Console.WriteLine(BUZZ); ++i;
Console.WriteLine(FIZZ); ++i;
Console.WriteLine(++i);
Console.WriteLine(++i);
Console.WriteLine(FIZZ); ++i;
Console.WriteLine(BUZZ); ++i;
Console.WriteLine(++i);
Console.WriteLine(FIZZ); ++i;
Console.WriteLine(++i);
Console.WriteLine(++i);
Console.WriteLine(FIZZBUZZ); ++i;
}
}
Take advantage of conditional format specifiers to get a nicely golfed version:
public void DoFizzBuzz()
{
for(int i=1;i<101;i++)Console.WriteLine("{0:#;}{1:;;Fizz}{2:;;Buzz}",i%3*i%5==0?0:i,i%3,i%5);
}
I think what you're trying to accomplish is a generic solution to FizzBuzz, that will work for any number of number-word combinations.
You have a good start - I think I can answer your questions with this example:
public void DoFizzBuzz()
{
var combinations = new List<Tuple<int, string>>
{
new Tuple<int, string> (3, "Fizz"),
new Tuple<int, string> (5, "Buzz"),
};
Func<int, int, bool> isMatch = (i, comb) => i % comb == 0;
for (int i = 1; i <= 100; i++)
{
Console.Write(i);
var matchingCombs = combinations.Where(c => isMatch(i, c.Item1)).ToList();
if (matchingCombs.Any())
{
Console.Write(string.Join("", matchingCombs.Select(c => c.Item2)));
}
else
{
Console.Write(i);
}
Console.Write(Environment.NewLine);
}
}
In practice, you would pass combinations in to the method, but I included it inside just to be concise.
3rd edit:
Here is one way to "get rid of the bool" from your version (that is replace the for loop in your original question with this):
for (int i = 1; i <= 100; i++)
{
var x = combinations.Where(n => i % n.Item1 == 0);
if (x.Count() == 0)
Console.Write(i);
else
Console.Write(string.Join("",x.Select(e => e.Item2)));
Console.Write(Environment.NewLine);
}
Prior answers:
For a pure C# solution check out Keith Thompson's solution.
using System;
class FizzBuzz {
static void Main() {
for (int n = 1; n <= 100; n ++) {
if (n % 15 == 0) {
Console.WriteLine("FizzBuzz");
}
else if (n % 3 == 0) {
Console.WriteLine("Fizz");
}
else if (n % 5 == 0) {
Console.WriteLine("Buzz");
}
else {
Console.WriteLine(n);
}
}
}
}
I worked a bit on FixBuzz using linq. These are the solutions I came up with -- I believe they represent the best way to express the solution to this problem using Linq. (GitHub)
using System;
using System.Linq;
class FizzBuzz {
static void Main() {
var list = Enumerable.Range(1,100)
.Select(n => {
if (n % 15 == 0) {
return "FizzBuzz";
}
if (n % 3 == 0) {
return "Fizz";
}
if (n % 5 == 0) {
return "Buzz";
}
return n.ToString();
});
foreach(string item in list)
Console.WriteLine(item);
}
}
and the crazy one line version:
using System;
using System.Linq;
class FizzBuzz {
static void Main() {
Console.WriteLine(
String.Join(
Environment.NewLine,
Enumerable.Range(1, 100)
.Select(n => n % 15 == 0 ? "FizzBuzz"
: n % 3 == 0 ? "Fizz"
: n % 5 == 0 ? "Buzz"
: n.ToString())
));
}
}
public void DoFizzBuzz()
{
for (int i = 1; i <= 100; i++)
{
if (i % 3 == 0)
Console.Write("Fizz");
if (i % 5 == 0)
Console.Write("Buzz");
if (!(i % 3 == 0 || i % 5 == 0))
Console.Write(i);
Console.Write(Environment.NewLine);
}
}
This gets rid of the bool found, but forces you to do duplicate evaluation. It is slightly different from some of the other answers using i % 15 == 0 for the FizzBuzz qualification. Whether or not this is better is up for debate. However, it is a different way.
Did anyone do this one already?
Enumerable.Range(1, 100).Select(x =>
(x % 15 == 0) ? "FIZZBUZZ"
: (x % 5 == 0) ? "BUZZ"
: (x % 3 == 0) ? "FIZZ"
: x.ToString()
)
.ToList()
.ForEach(console.WriteLine);
I think you started with a complicated way. Improving that code would be more complicated. You can use a temp variable to track and display that variable at the end of the FizzBuzz check. Below is code and you can also watch this detail c# FizzBuzz youtube video ( http://www.youtube.com/watch?v=OX5TM3q-JQg ) which explains how the below code is implemented.
for (int j = 1; j <= 100; j++)
{
string Output = "";
if (j % 3 == 0) Output = "Fizz";// Divisible by 3 --> Fizz
if (j % 5 == 0) Output += "Buzz"; // Divisible by 5 --> Buzz
if (Output == "") Output = j.ToString(); // If none then --> number
Console.WriteLine(Output); // Finally print the complete output
}
Will add my 5 cents to solution by Linq. Everybody is using Select, which is basically Map function. IMHO foldl function suits better to solve this quiz:
Console.WriteLine(
Enumerable
.Range(1, 100)
.Aggregate(new StringBuilder(), (builder, i)
=> i % 15 == 0 ? builder.AppendLine("FizzBuzz")
: i % 3 == 0 ? builder.AppendLine("Fizz")
: i % 5 == 0 ? builder.AppendLine("Buzz")
: builder.AppendLine(i.ToString()))
.ToString());
Linq:
Enumerable.Range(1, 100).ToList().ForEach(i => Console.WriteLine( i % 3 * i % 5 == 0 ? (i % 3 == 0 ? "Fizz" : "") + (i % 5 == 0 ? "Buzz" : "") : i.ToString()));
In my opinion, the FizzBuzz problem is always presented as a challenge to the interviwee to make the word FizzBuzz appear without explicitly printing it. Here is my solution in C#.
internal void PrintFizzBuzzAlternative(int num)
{
if (num % 5 == 0)
Console.Write("Fizz");
if (num % 3 == 0)
Console.Write("Buzz");
if (num % 5 != 0 && num % 3 != 0)
Console.Write(num);
Console.WriteLine();
}
Not the most efficient, but here's one using C#-6 string interpolation:
void Main()
{
for (int i = 1; i <= 100; i++)
{
Console.WriteLine($"{(i % 15 == 0 ? "FizzBuzz" :
i % 3 == 0 ? "Fizz" :
i % 5 == 0 ? "Buzz" : i.ToString())}");
}
}
Enumerable.Range(1, 100).ToList().ForEach(i=>Console.WriteLine($"{(i%3*i%5==0?0:i):#;}{i%3:;;Fizz}{i%5:;;Buzz}"));
This answer has it all:
LINQ
Conditional formatting
String interpolation
All on a single line
Victory!
The FizzBuzz question is a great interview question. We have started using it in our interview process. It is astounding how many people cannot solve such a simple problem.
Keep in mind, the original blog post was eventually locked due to a flood of people posting more solutions. Hahaha.
Regardless, here is mine in C++! ^_^
#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
for (int i = 1; i <= 100; ++i)
{
bool isMultipleOfThree = (i % 3) == 0;
bool isMultipleOfFive = (i % 5) == 0;
if (isMultipleOfThree) cout << "Fizz";
if (isMultipleOfFive) cout << "Buzz";
if (!isMultipleOfThree && !isMultipleOfFive) cout << i;
cout << '\n';
}
return 0;
}
Ok, what the heck, here's the solution I've come to like :)
public void DoFizzBuzz()
{
for (int i = 1; i <= 100; ++i)
{
bool isDivisibleByThree = i % 3 == 0;
bool isDivisibleByFive = i % 5 == 0;
if (isDivisibleByThree || isDivisibleByFive)
{
if (isDivisibleByThree)
cout << "Fizz";
if (isDivisibleByFive)
cout << "Buzz";
}
else
{
cout << i;
}
cout << endl;
}
}
Obviously, this is not the fastest solution, but I like it because it emphasizes readability and makes the "FizzBuzz" case no longer a special case, but something that will happen naturally through the code path.
In the end, what I love most about this question whenever it comes up is that we get to see just how many different solutions ppl can come up with.
I am a beginner, here is my attempt:
public void DoFizzBuzz()
{
for (int i = 1; i < 101; i++)
{
if ((i % 3 == 0) && (i % 5 == 0))
{
Console.WriteLine("{0} FizzBuzz", i);
}
else if (i % 3 == 0)
{
Console.WriteLine("{0} Fizz", i);
}
else if (i % 5 == 0)
{
Console.WriteLine("{0} Buzz", i);
}
else
{
Console.WriteLine(i);
}
}
Console.ReadLine();
}
Is there anything wrong with my approach?
Mine seems a lot simpler than everyone's else approach so it must be wrong.
You want probably make it configurable, but the question is what should be made configurable - we don't know that. Maybe we should make configurable all the cycle (FizzBuzz has the cycle). Here is very small and fun version with configurable cycle:
string[] fizzBuzzCycle =
"FizzBuzz,{0},{0},Fizz,{0},Buzz,Fizz,{0},{0},Fizz,Buzz,{0},Fizz,{0},{0}"
.Split(',');
for (int i = 1; i <= 100; i++)
Console.WriteLine(fizzBuzzCycle[i%fizzBuzzCycle.Length], i);
So if the strings or whole cycle should be changed it is easy to change. But you just don't know what to make configurable. Maybe condition will change: "for prime numbers print Pizz" and for this modification the solution by #ThomasLevesque is better, because it is easier to change.
I tried to solve this problem without looking at the answers.
It took me 3 hours to succeed. (I'm just a hobby programmer by the way so don't bash me hard please :))
This is my c# version solution:
static void Main(string[] args)
{
for (int i = 1; i <= 100; i++)
{
if( ((i % 3) != 0) && ((i % 5) != 0))
{
WriteLine($"{i}");
}
else
{
if ((i % 15) == 0)
{
WriteLine("FizzBuzz");
}
else if ((i % 3) == 0)
{
WriteLine("Fizz");
}
else if ((i % 5) == 0)
{
WriteLine("Buzz");
}
}
}
}
The null-coalescing operator is really useful:
string output = null;
for (int i = 1; i <= 100; i++)
{
if (i % 3 == 0) output += "fizz";
if (i % 5 == 0) output += "buzz";
Console.WriteLine(output ?? i.ToString());
output = null;
}
Console.ReadKey();
I recommend using the ++i instead of the i++ in a for loop because i++ requires a copy to be made ;)
public void DoFizzBuzz()
{
for (int i = 1; i < 101; ++i)
{
if (i % 15 == 0)
Console.WriteLine ("FizzBuzz");
else if (i % 3 == 0)
Console.WriteLine ("Fizz");
else if (i % 5 == 0)
Console.WriteLine ("Buzz");
else
Console.WriteLine (i);
}
}
With the input of Rob H and Jacob Krall here is what I have at the moment.
Perhaps I will play around with that in future... just wanted to provide it.
public void DoFizzBuzz()
{
// expect this to come in as parameter
var combinations = new Tuple<int, string>[]
{
new Tuple<int, string> (3, "Fizz"),
new Tuple<int, string> (5, "Buzz"),
};
Func<int, int, bool> isMatch = (i, comb) => i % comb == 0;
// expect the borders 1, 100 to come in as parameters
for (int i = 1; i <= 100; ++i)
{
var matchingCombs = combinations.Where(c => isMatch(i, c.Item1)).DefaultIfEmpty(new Tuple<int, string>(i, i.ToString())).Aggregate((v, w) => new Tuple<int, string>(v.Item1, v.Item2 + w.Item2)).Item2;
Console.WriteLine(matchingCombs);
}
}
I would suggest this compact code as an addition to the previous simple and nice versions.
for (int i = 1; i <= 100; i++) // i++ but not ++i as in your example, be careful here
{
bool fizz = i % 3 == 0;
bool buzz = i % 5 == 0;
string output = fizz && buzz ? "FizzBuzz" :
fizz ? "Fizz" :
buzz ? "Buzz" :
i.ToString();
Console.WriteLn(output);
}
A functional approach...
Console.WriteLine(Enumerable
.Range(1,100)
.Aggregate("",
(a,i) => a + "\n" + (i%15==0 ? "fizzbuzz" :
(i%5==0 ? "buzz" :
(i%3==0 ? "fizz" : i.ToString())))));
Obviously this is a bit outside the spirit of the FizzBuzz challenge. But in my benchmark this was the fastest I could make it while single threaded and still terminating at 100. It is semi-unrolled and uses a StringBuilder. It is approximately three times faster than the standard approach.
const string FIZZ = " Fizz\n";
const string BUZZ = " Buzz\n";
const string FIZZBUZZ = " FizzBuzz\n";
...
var sb = new StringBuilder();
int i = 0;
while(true)
{
sb.Append(i+3);
sb.Append(FIZZ);
sb.Append(i+5);
sb.Append(BUZZ);
sb.Append(i+6);
sb.Append(FIZZ);
sb.Append(i+9);
sb.Append(FIZZ);
sb.Append(i+10);
sb.Append(BUZZ);
if(i+12 > 100)
break;
sb.Append(i+12);
sb.Append(FIZZ);
i+=15;
sb.Append(i);
sb.Append(FIZZBUZZ);
}
Console.Write(sb.ToString());
Relatively simple solution using a for loop.
No Linq or anything - just basic shorthand if statements
for(int x=1;x<101;x++)
Console.WriteLine(x%3==0?"Fizz"+(x%5==0?"Buzz":""):x%5==0?"Buzz":x+"");
The Linq solution which is a lot like csells (sans string interpolation) and fits on one line would be:
Enumerable.Range(1,100).ToList().ForEach(x=>Console.WriteLine(x%3==0?"Fizz"+(x%5==0?"Buzz":""):x%5==0?"Buzz":x+""));
I'll add mine even though there's 20 other solutions already written:
It goes like this....
var x = 1;
while (x <= 100)
{
if (x % 3 == 0 && x % 5 == 0)
{Console.Writeline("FizzBuzz");}
else if (x % 3 == 0)
{Console.Writeline("fizz");}
else if (x % 5 == 0)
{Console.Writeline("Buzz");}
else
{Console.Writeline(x);}
x++
}
First solution I came up with. Simple, to the point and gets the job done. No need for bool.
This my effort mixing Func with IEnumerable
class Program
{
static void Main(string[] args)
{
foreach (var i in FizzBuzz(100))
{
Console.WriteLine(i);
}
}
private static IEnumerable<string> FizzBuzz(int maxvalue)
{
int count = 0;
//yield return count.ToString();
Func<int, string> FizzBuzz = (x) => ((x % 5 == 0 && x % 3 == 0) ? "FizzBuzz" : null);
Func<int, string> Buzz = (x) => ((x % 5 == 0) ? "Buzz" : null);
Func<int, string> Fizz = (x) => ((x % 3 == 0) ? "Fizz" : null);
Func<int, string> Number = (x) => x.ToString();
while (count < maxvalue)
{
count++;
yield return FizzBuzz(count) ?? Buzz(count) ?? Fizz(count) ?? Number(count);
}
}
}
The original questions were:
1.How to get rid of the bool found?
2.Is there a better way of testing than the foreach?
This gets rid of the bool and the foreach, and I think it's still readable.
public static void DoFizzBuzz()
{
var combinations = new Tuple<int, string>[]
{
new Tuple<int, string> (3, "Fizz"),
new Tuple<int, string> (5, "Buzz"),
};
for (int i = 1; i <= 100; i++)
{
var fb = combinations.Where(t => {
if (i % t.Item1 == 0)
{
Console.Write(t.Item2);
return true;
}
return false;
}).ToList();
if (!fb.Any())
{
Console.Write(i);
}
Console.Write(Environment.NewLine);
}
}
Who'd a thunk we'd be getting so excited about a simple kids game? :)
You can use either use this and only take the amount you want
static void Main(string[] args)
{
GetFizzBuzz().Take(100).ToList().ForEach(Console.WriteLine);
}
private static IEnumerable<string> GetFizzBuzz()
{
for (var i = 0; i < int.MaxValue; i++)
{
if (i % 3 == 0 && i % 5 == 0) yield return "FizzBuzz";
if (i % 3 == 0) yield return "Fizz";
yield return i % 5 == 0 ? "Buzz" : i.ToString(CultureInfo.InvariantCulture);
}
}
Or simply use this :
Enumerable.Range(1, 100).Select(s => {
if (s % 3 == 0 && s % 5 == 0) return "FizzBuzz";
if (s % 3 == 0) return "Fizz";
return s%5 == 0 ? "Buzz" : s.ToString(CultureInfo.InvariantCulture);
}).ToList().ForEach(Console.WriteLine);
With no if conditions, just one ternary operator.
string[] s = new string[6]{"Fizz", "Buzz", "", "", "", ""};
for (int i = 1; i <= 100; i++)
{
string output = s[(i%3)*2] + s[(i%5)+1];
Console.WriteLine(string.IsNullOrEmpty(output)? "" + i : output);
}

Categories