I'm learning how to program using c#. I'm really new to this.
My question is I'm trying to create an array that shows 10 numbers. I want my code to check which numbers below 10 are divisible for 3 or 5 and sum the total.
I've tried to use the .Sum() function but says int doesn't contain a definition for Sum. I've put using System.Linq on my program.
Does anyone have an idea how to make this sum happens?
{
int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int sum = 1 + 2;
foreach (int n in numbers)
{
if (n % 3 == 0 || n % 5 == 0)
{
int total = n.Sum();
Console.WriteLine(total);
}
else
{
Console.WriteLine("not divisible");
}
}`
So your problem is that you are trying to call .Sum() on a variable n which is of type int (you define it here: foreach (int n in numbers), and that is not a method.
Using LINQ you could do something like:
var numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var total = numbers.Where(n => n % 3 == 0 || n % 5 == 0).Sum();
If I understand it correct and using your code this is what you want.
int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int sum = 1 + 2;
int total=0;
foreach (int n in numbers)
{
if (n % 3 == 0 || n % 5 == 0)
{
int total += n;
}
else
{
Console.WriteLine("not divisible");
}
}
Console.WriteLine(total);
I moved the printing out to after the foreach so you get one result when it is done
Everybody forgot that array should contain 10 numbers but some numbers values maybe greater than 10. Only number values below 10 should be checked. So a right answer should be
var numbers = new int[] { 1, 9, 5, 6, 8, 10,4, 15, 25, 3};
var total = numbers.Where( n => (n<10) && ( n % 3 == 0 || n % 5 == 0)).Sum();
Related
I have an array of numbers {3, 6, 1, 5, 5, 6} I am trying to get every other number starting with the last number.
The correct result would then be 6, 5, 6 the only way I have been able to get this to work is to use Reverse.
int[] digitList = {3, 6, 1, 5, 5,6};
var rev = digitList.Reverse().Where((x, i) => i % 2 == 0).Reverse().ToList();
// Correct results in 6,5,6
var l = digitList.Where((x, i) => i % 2 == 0).ToList();
// Incorrect results in 3,1,5
Is there a way of doing this without the Reverse? How can i tell Where() to start at the other end?
If the count is odd, then every other number from the start, if it's even then take every other number from the second one (or skip the first), that removes the need for a reverse operation. For example:
int[] digitList = { 3, 6, 1, 5, 5, 6 };
//Skip 1 if count is odd, otherwise skip zero
var skipCount = digitList.Count() % 2 == 0 ? 1 : 0;
var l = digitList
.Skip(skipCount)
.Where((x, i) => i % 2 == 0)
.ToList();
You have to check for odd/even length arrays; to amend your current code you
should change the == 0 condition:
int[] digitList = { 3, 6, 1, 5, 5, 6, 7, 8 };
var rev = digitList
.Where((x, i) => i % 2 != digitList.Length % 2) // not "== 0"
.ToList();
I'd like to know the best way to approach this. I have an integer array (say of 3, 4, 8, 10, 15, 24, 29, 30) and I want to sort it into 3 groups: 4 times table, 5 times table, and neither).
As the groups would suggest, it would sort the array into the 4 and 5 times table with another for items that aren't present in either.
What's the best way to approach this in C#? I'm currently using this:
int[] iArray = new int[]{3, 4, 8, 10, 15, 24, 29, 30};
var iE = iArray.GroupBy ((e) => {
if (e % 4 == 0) {
return "four";
} else if (e % 5 == 0) {
return "five";
} else {
return "other";
}
}).OrderBy (e => e.Count ());
Produces:
4
4
8
24
5
10
15
30
Other
3
29
int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 };
If you want to get all multiples of 4 and all multiples of 5 (and have some overlap between the two) you can do this:
List<int> multiplesOf4 = (from i in arr where i % 4 == 0 select i).ToList();
List<int> multiplesOf5 = (from i in arr where i % 5 == 0 select i).ToList();
List<int> others = (from i in arr where i % 5 != 0 && i % 4 != 0 select i).ToList();
If you want no overlap, however, you need to pick which one will be dominant. I chose 4 here:
List<int> multiplesOf4 = new List<int>(),
multiplesOf5 = new List<int>(),
others = new List<int>();
foreach (int i in arr)
{
if (i % 4 == 0)
multiplesOf4.Add(i);
else if (i % 5 == 0)
multiplesOf5.Add(i);
else
others.Add(i);
}
Try this:
var numberGroupsTimes5 =
from n in numbers
group n by n % 5 into g
where g.Key == 0
select new { Remainder = g.Key, Numbers = g };
var numberGroupsTimes4 =
from n in numbers
group n by n % 4 into g
where g.Key == 0
select new { Remainder = g.Key, Numbers = g };
foreach (var g in numberGroupsTimes5)
{
string st = string.Format("Numbers with a remainder of {0} when divided by 5:" , g.Remainder);
MessageBox.Show("" + st);
foreach (var n in g.Numbers)
{
MessageBox.Show(""+n);
}
}
foreach (var g in numberGroupsTimes4)
{
string st = string.Format("Numbers with a remainder of {0} when divided by 4:", g.Remainder);
MessageBox.Show("" + st);
foreach (var n in g.Numbers)
{
MessageBox.Show("" + n);
}
}
You approach is correct. But you can do some small improvements to make it more readable and standard:
var iArray = new[] { 3, 4, 8, 10, 15, 24, 29, 30 };//Don't need to give type(int) explicitly
var iE = iArray.GroupBy(e => e % 4 == 0 ? "four" : e % 5 == 0 ? "five" : "other").OrderBy(e => e.Count());
It'll give the same results.
Let's say I have a list of numbers like
1 2 3 4 5 6 7 8 9 10
Now I want to delete 50% of the list so i would have now a list like
1 3 5 7 9
I don't want to remove the first 50% , so not this
6 7 8 9 10
I want to regularly delete from the list.
I'm trying to implement this in C# or JAVA.
I know that sometime is not possible to remove that percent exactly but something close will be ok.
My procent is always an integer, so is from 0 to 100 .
I'm trying to do this with an N percent for a list, how should I start?
You can use Linq:
List<int> source = new List<int>() {
1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// Take every other item from the list
List<int> result = source
.Where((item, index) => index % 2 == 0)
.ToList();
General case should be elaborated a little bit:
int percent = 50;
List<int> result = source
.Where((item, index) =>
(index == 0) ||
(index * percent / 100) > ((index - 1) * percent / 100))
.ToList();
int halfNumOfList = myList.Count / 2;
int itemsRemoved = 0;
for (int i = 0; i < myList.Count; i++)
{
if (itemsRemoved < halfNumOfList)
{
if (i % 2 != 0)
{
myList.Remove(myList[i]);
itemsRemoved++;
}
}
}
Suppose I have this number list:
List<int> = new List<int>(){3,5,8,11,12,13,14,21}
Suppose that I want to get the closest number that is less than 11, it would be 8
Suppose that I want to get the closest number that is greater than 13 that would be 14.
The numbers in list can't be duplicated and are always ordered. How can I write Linq for this?
with Linq assuming that the list is ordered I would do it like this:
var l = new List<int>() { 3, 5, 8, 11, 12, 13, 14, 21 };
var lessThan11 = l.TakeWhile(p => p < 11).Last();
var greaterThan13 = l.SkipWhile(p => p <= 13).First();
EDIT:
As I have received negative feedback about this answer and for the sake of people that may see this answer and while it's accepted don't go further, I explored the other comments regarding BinarySearch and decided to add the second option in here (with some minor change).
This is the not sufficient way presented somewhere else:
var l = new List<int>() { 3, 5, 8, 11, 12, 13, 14, 21 };
var indexLessThan11 = ~l.BinarySearch(10) -1;
var value = l[indexLessThan11];
Now the code above doesn't cope with the fact that the value 10 might actually be in the list (in which case one shouldn't invert the index)! so the good way is to do it:
var l = new List<int>() { 3, 5, 8, 11, 12, 13, 14, 21 };
var indexLessThan11 = l.BinarySearch(10);
if (indexLessThan11 < 0) // the value 10 wasn't found
{
indexLessThan11 = ~indexLessThan11;
indexLessThan11 -= 1;
}
var value = l[indexLessThan11];
I simply want to note that:
l.BinarySearch(11) == 3
//and
l.BinarySearch(10) == -4;
Use Array.BinarySearch - no need for LINQ or visiting on average half the elements to find your target.
There are also a variety of SortedXXX classes that may be suitable for what you're doing [that will have such efficient O(log N) searches built-in]
You can do this using a binary search. If your searching for 11, well obviously you'll get the index your after. If you search for 10 and use the bitwise complement of the result, you'll get the closest match.
List<int> list = new List<int>(){3,5,8,11,12,13,14,21};
list.Sort();
int index = list.BinarySearch(10);
int found = (~index)-1;
Console.WriteLine (list[found]); // Outputs 8
The same goes searching in the other direction
int index = list.BinarySearch(15);
Console.WriteLine("Closest match : " + list[+~index]); // Outputs 21
Binary searches are also extremely fast.
closest number below 11:
int someNumber = 11;
List<int> list = new List<int> { 3, 5, 8, 11, 12, 13, 14, 21 };
var intermediate = from i in list
where i < someNumber
orderby i descending
select i;
var result = intermediate.FirstOrDefault();
closest number above 13:
int someNumber = 13;
List<int> list = new List<int> { 3, 5, 8, 11, 12, 13, 14, 21 };
var intermediate = from i in list
where i > someNumber
orderby i
select i;
var result = intermediate.FirstOrDefault();
This is my answer
List<int> myList = new List<int>() { 3, 5, 8, 11, 12, 13, 14, 21 };
int n = 11;
int? smallerNumberCloseToInput = (from n1 in myList
where n1 < n
orderby n1 descending
select n1).First();
int? largerNumberCloseToInput = (from n1 in myList
where n1 > n
orderby n1 ascending
select n1).First();
var list = new List<int> {14,2,13,11,5,8,21,12,3};
var tested = 11;
var closestGreater = list.OrderBy(n => n)
.FirstOrDefault(n => tested < n); // = 12
var closestLess = list.OrderByDescending(n => n)
.FirstOrDefault(n => tested > n); // = 8
if (closestGreater == 0)
System.Diagnostics.Debug.WriteLine(
string.Format("No number greater then {0} exists in the list", tested));
if (closestLess == 0)
System.Diagnostics.Debug.WriteLine(
string.Format("No number smaler then {0} exists in the list", tested));
Here is my way hope this helps somebody!
List<float> list = new List<float> { 4.0f, 5.0f, 6.0f, 10.0f, 4.5f, 4.0f, 5.0f, 6.0f, 10.0f, 4.5f, 4.0f, 5.0f, 6.0f, 10.0f };
float num = 4.7f;
float closestAbove = list.Aggregate((x , y) => (x < num ? y : y < num ? x : (Math.Abs(x - num)) < Math.Abs(y - num) ? x : y));
float closestBelow = list.Aggregate((x , y) => (x > num ? y : y > num ? x : (Math.Abs(x - num)) < Math.Abs(y - num) ? x : y));
Console.WriteLine(closestAbove);
Console.WriteLine(closestBelow);
This means you dont have to order the list
Credit: addapted from here: How to get the closest number from a List<int> with LINQ?
The Expanded Code
float closestAboveExplained = list.Aggregate((closestAbove , next) => {
if(next < num){
return closestAbove;
}
if(closestAbove < num){
return next;
}
else{
if(Math.Abs(closestAbove - num) < Math.Abs(next - num)){
return closestAbove;
}
}
return next;
});
You can use a query for this such as:
List<int> numbers = new List<int>() { 3, 5, 8, 11, 12, 13, 14, 21 };
List<int> output = (from n in numbers
where n > 13 // or whatever
orderby n ascending //or descending
select n).ToList();
If Start=0 and Count=10 then how to get the alternate values using Enumerable.Range()
the out put should be like { 0, 2, 4, 6, 8 }
and if Start=1 and Count=10 then { 1, 3, 5, 7, 9 }
The continuous value can be get like
var a = Enumerable.Range(0,10).ToList();
but how to get the alternate values?
Halving the number of items that Range should generate (its second parameter) and then doubling the resulting values will give both the correct number of items and ensure an increment of 2.
Enumerable.Range(0,5).Select(x => x * 2)
Enumerable.Range(0, 10).Where(i => i % 2 == 0); // { 0, 2, 4, 6, 8 }
Enumerable.Range(0, 10).Where(i => i % 2 != 0); // { 1, 3, 5, 7, 9 }
The count parameter in your code looks like an end point of the loop.
public static MyExt
{
public static IEnumerable<int> Range(int start, int end, Func<int, int> step)
{
//check parameters
while (start <= end)
{
yield return start;
start = step(start);
}
}
}
Usage: MyExt.Range(1, 10, x => x + 2) returns numbers between 1 to 10 with step 2
MyExt.Range(2, 1000, x => x * 2) returns numbers between 2 to 1000 with multiply 2 each time.
What you are after here does not exist in the BCL as far as I'm aware of, so you have to create your own static class like this to achieve the required functionality:
public static class MyEnumerable {
public static IEnumerable<int> AlternateRange(int start, int count) {
for (int i = start; i < start + count; i += 2) {
yield return i;
}
}
}
Then you can use it like this wherever you want to:
foreach (int i in MyEnumerable.AlternateRange(0, 10)) {
//your logic here
}
You can then also perform LINQ queries using this since it returns IEnumerable
So if you want you can also write the above like this if you want to exclude the number 6
foreach (int i in MyEnumerable.AlternateRange(0, 10).Where( j => j != 6)) {
//your logic here
}
I hope this is what you are after.
You can't have this as an extension method on the Enumerable class directly since that is a static class, and extension methods work on an object of a class, and not the class itself. That's why you have to create a new static class to hold this method if you want to mimic the Enumerable class.
This can be done more simply using Linq and by specifying the minimum, length, and step values:
Enumerable.Range(min, length).Where(i => (i - min) % step == 0);
Usage with 0 through 10 at a step size of 2:
var result = Enumerable.Range(0, 10).Where(i => (i - 10) % 2 == 0);
Output:
0, 2, 4, 6, 8
Usage with 1 through 10 at a step size of 2:
var result = Enumerable.Range(1, 10).Where(i => (i - 10) % 2 == 0);
Output:
1, 3, 5, 7, 9
You could go further and make a simple function to output it using a minimum, maximum, and step value:
public static IEnumerable<int> RangedEnumeration(int min, int max, int step)
{
return Enumerable.Range(min, max - min + 1).Where(i => (i - min) % step == 0);
}
The reason to set the range length to max - min + 1 is to ensure the max value is inclusive. If the max should be exclusive, remove the + 1.
Usage:
var Result = RangedEnumeration(0, 10, 2); // 0, 2, 4, 6, 8, 10
var Result = RangedEnumeration(1, 10, 2); // 1, 3, 5, 7, 9
var Result = RangedEnumeration(1000, 1500, 150); // 1000, 1150, 1300, 1450