Even number's sum from an integer - c#

How to get the even number' sum from an integer input.
var intInput = 10;
Now i want the even' sum. In this case = 2+4+6+8+10 = 30
var evenCount = 0;
if (i % 2==0)
{
evenCount = evenCount + i;
}
How to achieve this?

var evenCount = (intInput / 2) * (intInput / 2 + 1);
This is just twice the sum of all the integers from zero to half the specified number.
2+4+6+8+10 = 2 (1+2+3+4+5)

How about this?
var sum = Enumerable.Range(1,10).Where(x=> x%2==0).Sum();

int intInput=10;
var evenCount = 0;
for (int i=1;i<=intInput;i++)
{
if (i % 2==0)
{
evenCount = evenCount + i;
}
}

Try
var intInput =10;
var evenValueSum = 0;
for(int i=intInput ;i>0;i--)
{
if(i %2 ==0)
{
evenValueSum += i;
}
}

int end = inputNum / 2;
int sum = 0;
for(int i = 1; i <= end; i++)
sum += i * 2;

int evenCount = 0;
int countFrom = 1;
int countTo = 10;
for (int i = countFrom; i <= countTo; i++) {
if (i % 2 == 0) {
evenCount += i
}
}

Related

Can someone say what i do wrong in C# task?

I need make symmetric letter “W” in string Array
get_w() Is method that should return string array that contains letter "W"
get_w(5) # should return:
public string[] GetW(int h)
{
if (h < 2) return new string[h];
int row = 0;
int stars_number = h * 4 - 3;
int times = 0;
StringBuilder[] c = new StringBuilder[h];
for(int a = 0; a < h; a++)
{
c[a] = new StringBuilder();
c[a].Length = stars_number;
}
for (int i = 0; i < stars_number; i++)
{
if (i == h - 1) times = 1;
if (i == stars_number-2 * h + 1) times = 2;
if (i == stars_number - h) times = 3;
c[row][i] = '*';
if (row < h - 1 && (times == 0 || times == 2))
{
row += 1;
}
else
{
row -= 1;
}
}
string []str = new string[h];
for(int i = 0; i < h; i ++)
{
str[i] = c[i].ToString();
}
return str;
}
if I compile it in a VS i get no errors.Here is an example of the result
This task is taken from the Codewars
but if I try to test on Codewars with the code I described above, I get this error
Edited:I changed returning array with "h" length to empty array and had got this
i found the task solution by replacing charters that equal '\0' with character ' '
here is working code
public string[] GetW(int h)
{
if (h < 2) return new string[]{};
int row = 0;
int stars_number = h * 4 - 3;
int times = 0;
StringBuilder[] c = new StringBuilder[h];
for(int a = 0; a < h; a++)
{
c[a] = new StringBuilder();
c[a].Length = stars_number;
}
for (int i = 0; i < stars_number; i++)
{
if (i == h - 1) times = 1;
if (i == stars_number-2 * h + 1) times = 2;
if (i == stars_number - h) times = 3;
c[row][i] = '*';
if (row < h - 1 && (times == 0 || times == 2))
{
row += 1;
}
else
{
row -= 1;
}
}
string []str = new string[h];
for(int i = 0; i < h; i ++)
{
c[i].Replace('\0', ' ');
str[i] = c[i].ToString();
}
return str;
}
And here is result of test

Sum of 1000 first primes gives wrong output

i have written a small program to print out the sum of the 1000 first primes, but for some reason i get the wrong result.
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
long sum;
sum = 0;
int count;
count = 0;
for (long i = 0; count <= 1000; i++)
{
bool isPrime = true;
for (long j = 2; j < i; j++)
{
if (i != j && i % j == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
{
sum += i;
count++;
}
}
Console.WriteLine(string.Format("{0}",sum));
Console.ReadLine();
}
}
}
result = 3674995 expected = 3682913
The implementation is identifying 1 as a prime, which is not correct; this can be fixed by initializing isPrime as follows.
bool isPrime = i != 1;
This yields the desired result 3682913; however the summand of 0 is also taken into account.
An efficient implementation checks for just prime divisors up to square root of the value; please, notice that all even values are not primes (with only exception - 2):
int count = 1000;
List<long> primes = new List<long>(count) {
2 }; // <- the only even prime
for (long value = 3; primes.Count < count; value += 2) {
long n = (long) (Math.Sqrt(value) + 0.1);
foreach (var divisor in primes)
if (divisor > n) {
primes.Add(value);
break;
}
else if (value % divisor == 0)
break;
}
// 3682913
Console.WriteLine(string.Format("{0}", primes.Sum()));
Console.ReadLine();
Try count = 1000000 and you'll get 7472966967499
long sum;
sum = 0;
int count;
count = 0;
for (long i = 0; count <= 1000; i++)
{
if (i == 1) continue;
bool isPrime = true;
for (long j = 2; j < i; j++)
{
if (i != j && i % j == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
{
sum += i;
count++;
}
}
Console.WriteLine(string.Format("{0}", sum));
Console.ReadLine();

How to process an array correctly

Here's the part 1 of my question, if you wanna check the background of this question :
Detecting brackets in input string
Forgive me if the title doesn't match, since I also confused how to name it appropriately to picture my problem. If anyone knows a more appropriate title, feel free to edit.
So, given below code (my own code) :
private const int PARTICLE_EACH_CHAR = 4;
/*ProcessBarLines : string s only contains numbers, b, [, and ]*/
private int ProcessBarLines(Canvas canvas, string s, int lastLineAboveNotation)
{
List<int> bracket = new List<int>();
List<int> other = new List<int>();
int currentCloseNumber = 0;
int currentOpenNumber = 0;
for (int i = 0; i < s.Length; i++)
{
if (s[i] == '[')
{
bracket.Add(i);
currentOpenNumber++;
if (i - 1 > 0 && s[i - 1] != '[')
{
currentOpenNumber = 1;
}
}
else if (s[i] == ']')
{
bracket.Add(i);
currentCloseNumber++;
if (i + 1 >= s.Length || s[i + 1] != ']' || currentOpenNumber == currentCloseNumber)
{
int min = bracket.Count - (currentCloseNumber * 2);
int max = bracket[bracket.Count - 1];
List<int> proc = new List<int>();
int firstIndex = -1;
int lastIndex = -1;
for (int ii = 0; ii < other.Count; ii++)
{
if (other[ii] > min && other[ii] < max)
{
proc.Add(other[ii]);
if (firstIndex == -1)
{
firstIndex = ii;
lastIndex = ii;
}
else
{
lastIndex = ii;
}
}
}
double leftPixel = firstIndex * widthEachChar;
double rightPixel = (lastIndex * widthEachChar) + widthEachChar;
DrawLine(canvas, currentCloseNumber, leftPixel,
rightPixel, lastLineAboveNotation * heightEachChar / PARTICLE_EACH_CHAR);
lastLineAboveNotation += currentCloseNumber - 1;
currentOpenNumber -= currentCloseNumber;
currentCloseNumber = 0;
}
}
else
{
other.Add(i);
}
}
return lastLineAboveNotation + 1;
}
Here's the test cases :
Picture 1 & 2 is the correct answer, and picture 3 is the wrong answer. Picture 3 should have a line, just like inverted from number 2, but, apparently, (if you look closely) the line is drawn on the right, but it should be on the left to be correct (above 0).
I figured, the problem is, I'm quite sure on the "min". Since it doesn't give the correct starting value.
Any idea on this? Feel free to clarify anything. It's used for writing numeric musical scores.
Btw, DrawLine() just meant to draw the line above the numbers, it's not the problem.
Finally! I found it!
private int ProcessBarLines(Canvas canvas, string s, int lastLineAboveNotation)
{
List<int> bracket = new List<int>();
List<int> other = new List<int>();
int currentCloseNumber = 0;
int currentOpenNumber = 0;
int space = 0;
for (int i = 0; i < s.Length; i++)
{
if (s[i] == '[')
{
bracket.Add(i);
currentOpenNumber++;
if (i - 1 > 0 && s[i - 1] != '[')
{
currentOpenNumber = 1;
}
}
else if (s[i] == ']')
{
bracket.Add(i);
currentCloseNumber++;
if (i + 1 >= s.Length || s[i + 1] != ']' || currentOpenNumber == currentCloseNumber)
{
int min = bracket[Math.Max(bracket.Count - ((currentCloseNumber * 2) + space), 0)];
int max = bracket[bracket.Count - 1];
space = max - min - 1;
List<int> proc = new List<int>();
int firstIndex = -1;
int lastIndex = -1;
for (int ii = 0; ii < other.Count; ii++)
{
if (other[ii] > min && other[ii] < max)
{
proc.Add(other[ii]);
other[ii] = -1;
if (firstIndex == -1)
{
firstIndex = ii;
lastIndex = ii;
}
else
{
lastIndex = ii;
}
}
}
double leftPixel = firstIndex * widthEachChar;
double rightPixel = (lastIndex * widthEachChar) + widthEachChar;
DrawLine(canvas, currentCloseNumber, leftPixel,
rightPixel, lastLineAboveNotation * heightEachChar / PARTICLE_EACH_CHAR);
lastLineAboveNotation += 1;
currentOpenNumber -= currentCloseNumber;
currentCloseNumber = 0;
}
}
else
{
other.Add(i);
}
}
return lastLineAboveNotation + 1;
}
If someone got a more efficient code, please let us know!

How to find the Largest Difference in an Array

Suppose I have an array of integers:
int[] A = { 10, 3, 6, 8, 9, 4, 3 };
My goal is to find the largest difference between A[Q] and A[P] such that Q > P.
For example, if P = 2 and Q = 3, then
diff = A[Q] - A[P]
diff = 8 - 6
diff = 2
If P = 1 and Q = 4
diff = A[Q] - A[P]
diff = 9 - 3
diff = 6
Since 6 is the largest number between all the difference, that is the answer.
My solution is as follows (in C#) but it is inefficient.
public int solution(int[] A) {
int N = A.Length;
if (N < 1) return 0;
int difference;
int largest = 0;
for (int p = 0; p < N; p++)
{
for (int q = p + 1; q < N; q++)
{
difference = A[q] - A[p];
if (difference > largest)
{
largest = difference;
}
}
}
return largest;
}
How can I improve this so it will run at O(N)? Thanks!
Simply getting the max and min wont work. Minuend (Q) should come after the Subtrahend (P).
This question is based on the "Max-profit" problem in codility (http://codility.com/train/). My solution only scored 66%. It requires O(N) for a score of 100%.
The following code runs in O(n) and should conform to the specification (preliminary tests on codility were successful):
public int solution(int[] A)
{
int N = A.Length;
if (N < 1) return 0;
int max = 0;
int result = 0;
for(int i = N-1; i >= 0; --i)
{
if(A[i] > max)
max = A[i];
var tmpResult = max - A[i];
if(tmpResult > result)
result = tmpResult;
}
return result;
}
Update:
I submitted it as solution and it scores 100%.
Update 02/26/16:
The original task description on codility stated that "each element of array A is an integer within the range [0..1,000,000,000]."
If negative values would have been allowed as well, the code above wouldn't return the correct value. This could be fixed easily by changing the declaration of max to int max = int.MinValue;
Here is the O(n) Java implementation
public static int largestDifference(int[] data) {
int minElement=data[0], maxDifference=0;
for (int i = 1; i < data.length; i++) {
minElement = Math.min(minElement, data[i]);
maxDifference = Math.max(maxDifference, data[i] - minElement);
}
return maxDifference;
}
After some attempts, I end up with this:
int iMax = N - 1;
int min = int.MaxValue, max = int.MinValue;
for (int i = 0; i < iMax; i++) {
if (min > A[i]) min = A[i];
if (max < A[N - i - 1]){
iMax = N - i - 1;
max = A[iMax];
}
}
int largestDiff = max - min;
NOTE: I have just tested it with some cases. Please if you find any case in which it doesn't work, let me know in the comment. I'll try to improve it or remove the answer. Thanks!
int FirstIndex = -1;
int SecondIndex = -1;
int diff = 0;
for (int i = A.Length-1; i >=0; i--)
{
int FirstNo = A[i];
int tempDiff = 0;
for (int j = 0; j <i ; j++)
{
int SecondNo = A[j];
tempDiff = FirstNo - SecondNo;
if (tempDiff > diff)
{
diff = tempDiff;
FirstIndex = i;
SecondIndex = j;
}
}
}
MessageBox.Show("Diff: " + diff + " FirstIndex: " + (FirstIndex+1) + " SecondIndex: " + (SecondIndex+1));
PHP Solution
<?php
$a = [0,5,0,5,0];
$max_diff = -1;
$min_value = $a[0];
for($i = 0;$i<count($a)-1;$i++){
if($a[$i+1] > $a[$i]){
$diff = $a[$i+1] - $min_value;
if($diff > $max_diff){
$max_diff = $diff;
}
} else {
$min_value = $a[$i+1];
}
}
echo $max_diff;
?>
We can do it in a much simpler way by calculating biggest and smallest element of the array. I know that you're also looking for time complexity. But for anyone looking to understand and solve this problem in a simple and easy to understand way, then here is my code:
#include<stdio.h>
#define N 6
int main()
{
int num[N], i, big, small, pos = 0;
printf("Enter %d integer numbers\n", N);
for(i = 0; i < N; i++)
scanf("%d", &num[i]);
big = small = num[0];
for(i = 1; i < N; i++)
{
if(num[i] > big)
{
big = num[i];
pos = i;
}
}
for(i = 1; i < pos; i++)
{
if(num[i] < small)
small = num[i];
}
printf("The largest difference is %d, ", (big - small));
printf("and its between %d and %d.\n", big, small);
return 0;
}
Output:
Enter 6 integer numbers
7
9
5
6
13
2
The largest difference is 8, and its between 13 and 5.
Source: C Program To Find Largest Difference Between Two Elements of Array
C++ solution for MaxProfit of codility test task giving 100/100 https://app.codility.com/programmers/lessons/9-maximum_slice_problem/max_profit/
int Max(vector<int> &A)
{
if (A.size() == 1 || A.size() == 0)
return 0;
int min_price = A[0];
int max_val = 0;
for (int i = 1; i < A.size(); i++)
{
max_val = std::max(max_val, A[i] - min_price);
min_price = std::min(min_price, A[i]);
}
return max_val;
}
My 100% JavaScript solution with O(N) time complexity:
function solution(A) {
// each element of array A is an integer within the range [0..200,000]
let min = 200000;
// The function should return 0 if it was impossible to gain any profit.
let maxDiff = 0;
for (const a of A) {
min = Math.min(min, a);
// find the maximum positive difference (profit) between current global minimum and current value of a
maxDiff = Math.max(maxDiff, a - min);
}
return maxDiff;
}
function solution(A) {
var n = A.length;
var min = Infinity, max = -Infinity, maxNet=0;
// find smallest and largest in the array following each other
for(let i = 0; i < n; i++){
if(A[i]<min) { // if you are updating the min you cannot consider the old max
min = A[i];
max = -Infinity;
} else if(A[i]> max){
max = A[i];
}
if(max!=-Infinity && max-min>maxNet) maxNet = max-min;
}
return maxNet;
}
PHP solution for MaxProfit of codility test task giving 100/100 found at http://www.rationalplanet.com/php-related/maxprofit-demo-task-at-codility-com.html
function solution($A) {
$cnt = count($A);
if($cnt == 1 || $cnt == 0){
return 0;
}
$max_so_far = 0;
$max_ending_here = 0;
$min_price = $A[0];
for($i = 1; $i < $cnt; $i++){
$max_ending_here = max(0, $A[$i] - $min_price);
$min_price = min($min_price, $A[$i]);
$max_so_far = max($max_ending_here, $max_so_far);
}
return $max_so_far;
}
100% score JavaScript solution.
function solution(A) {
if (A.length < 2)
return 0;
// Init min price and max profit
var minPrice = A[0];
var maxProfit = 0;
for (var i = 1; i < A.length; i++) {
var profit = A[i] - minPrice;
maxProfit = Math.max(maxProfit, profit);
minPrice = Math.min(minPrice, A[i]);
}
return maxProfit;
}
Python solution
def max_diff_two(arr):
#keep tab of current diff and min value
min_value = arr[0]
#begin with something
maximum = arr[1] - arr[0]
new_min = min_value
for i,value in enumerate(arr):
if i == 0:
continue
if value < min_value and value < new_min:
new_min = value
current_maximum = value - min_value
new_maximum = value - new_min
if new_maximum > current_maximum:
if new_maximum > maximum:
maximum = new_maximum
min = new_min
else:
if current_maximum > maximum:
maximum = current_maximum
return maximum
100% for Javascript solution using a more elegant functional approach.
function solution(A) {
var result = A.reverse().reduce(function (prev, val) {
var max = (val > prev.max) ? val : prev.max
var diff = (max - val > prev.diff) ? max - val : prev.diff
return {max: max, diff: diff}
}, {max: 0, diff: 0})
return result.diff
}

Circular moving average filter in LINQ

I'm looking for an elegant way to implement a moving average filter in c#. Now, that would be easy, but at the borders, the averaging window shall wrap around the start/end. This kind of made my code ugly and unintuitive, and I was wondering whether there was a smarter way to solve this using LINQ or so.
So what I currently have is:
// input is a List<double> y, output is List<double> yfiltered
int yLength = y.Count;
for (int i = 0; i < yLength; i++)
{
double sum = 0.0;
for (int k = i - halfWindowWidth; k <= i + halfWindowWidth; k++)
{
if (k < 0)
{
// k is negative, wrap around
sum += y[yLength - 1 + k];
}
else if (k >= yLength)
{
// k exceeds y length, wrap around
sum += y[k - yLength];
}
else
{
// k within y.Count
sum += y[k];
}
}
yfiltered[i] = sum / (2 * halfWindowWidth + 1);
}
Here is a completely other suggestion -
I was trying to actually make it better, rather than more readable.
The problem with your current code is that it sums up many numbers again and again, when not really needed.
Comparing both approaches after the implementation code...
I'm only summing a bunch for the first time, and then subtracting the tail and adding the head, again and again:
double sum = 0;
// sum = Enumerable.Range(i - halfWindowWidth, halfWindowWidth * 2 + 1)
// .Select(k => y[(k + yLength) % yLength]).Sum();
for (var i = -halfWindowWidth; i <= halfWindowWidth; i++)
{
sum += y[(i + yLength) % yLength];
}
yFiltered[0] = sum / (2 * halfWindowWidth + 1);
for (var i = 1; i < yLength; i++)
{
sum = sum -
y[(i - halfWindowWidth - 1 + yLength) % yLength] +
y[(i + halfWindowWidth) % yLength];
yFiltered[i] = sum / (2 * halfWindowWidth + 1);
}
And here are the speed tests, comparing the full-recalculation approach vs. this one:
private static double[] Foo1(IList<double> y, int halfWindowWidth)
{
var yfiltered = new double[y.Count];
var yLength = y.Count;
for (var i = 0; i < yLength; i++)
{
var sum = 0.0;
for (var k = i - halfWindowWidth; k <= i + halfWindowWidth; k++)
{
sum += y[(k + yLength) % yLength];
}
yfiltered[i] = sum / (2 * halfWindowWidth + 1);
}
return yfiltered;
}
private static double[] Foo2(IList<double> y, int halfWindowWidth)
{
var yFiltered = new double[y.Count];
var windowSize = 2 * halfWindowWidth + 1;
double sum = 0;
for (var i = -halfWindowWidth; i <= halfWindowWidth; i++)
{
sum += y[(i + y.Count) % y.Count];
}
yFiltered[0] = sum / windowSize;
for (var i = 1; i < y.Count; i++)
{
sum = sum -
y[(i - halfWindowWidth - 1 + y.Count) % y.Count] +
y[(i + halfWindowWidth) % y.Count];
yFiltered[i] = sum / windowSize;
}
return yFiltered;
}
private static TimeSpan TestFunc(Func<IList<double>, int, double[]> func, IList<double> y, int halfWindowWidth, int iteration
{
var sw = Stopwatch.StartNew();
for (var i = 0; i < iterations; i++)
{
var yFiltered = func(y, halfWindowWidth);
}
sw.Stop();
return sw.Elapsed;
}
private static void RunTests()
{
var y = new List<double>();
var rand = new Random();
for (var i = 0; i < 1000; i++)
{
y.Add(rand.Next());
}
var foo1Res = Foo1(y, 100);
var foo2Res = Foo2(y, 100);
Debug.WriteLine("Results are equal: " + foo1Res.SequenceEqual(foo2Res));
Debug.WriteLine("Foo1: " + TestFunc(Foo1, y, 100, 1000));
Debug.WriteLine("Foo2: " + TestFunc(Foo2, y, 100, 1000));
}
Time complexities:
MyWay: O(n + m)
OtherWay: O(n * m)
Since Foo1 is O(n * m) and Foo2 is O(n + m) it's really not surprising that the difference is huge.
Results on this not really crazy big scale are:
Results are equal: True
Foo1: 5.52 seconds
Foo2: 61.1 milliseconds
And on a bigger scale (replaced 1000 with 10000 on both iterations and count):
Foo1: Stopped after 10 minutes...
Foo2: 6.9 seconds
Expanding on my comment, you could use the mod (%) operator to get k to wrap
from 0 to ylength - 1
// input is a List<double> y, output is List<double> yfiltered
int yLength = y.Count;
for (int i = 0; i < yLength; i++)
{
double sum = 0.0;
for (int k = i - halfWindowWidth; k <= i + halfWindowWidth; k++)
{
sum += y[(k + yLength) % yLength];
}
yfiltered[i] = sum / (2 * halfWindowWidth + 1);
}
for (var i = 0; i < yLength; i++)
{
var sum = Enumerable.Range(i - halfWindowWidth, halfWindowWidth * 2 + 1)
.Select(k => y[(yLength + k) % yLength]).Sum();
yFiltered[i] = sum / (2 * halfWindowWidth + 1);
}
Or even:
var output = input.Select((val, i) =>
Enumerable.Range(i - halfWindowWidth, halfWindowWidth * 2 + 1)
.Select(k => input[(input.Count + k) % input.Count])
.Sum()).ToList();

Categories

Resources