so I am trying to take all the numbers from a list that are less than 5 and I try to put them in another list and print that list. I have no idea how to do that in c#. I will be very grateful if you'd help me. Thank you and here is my code:
using System;
namespace exercices
{
class Hello
{
static void Main(string[] args)
{
int[] a = { 1, 2, 3, 4, 5, 6, };
int[] b = { };
for (int i = 0; i < a.Length; i++)
{
if (a[i] < 5)
{
b.Append(a[i]);
}
}
}
}
Method 1. Just check every element
You should use List<T> collection in this method. It's possible to convert it to array later, if you need.
List<int> b = new();
foreach (int element in a)
{
if (element < 5)
{
b.Add(element);
}
}
Method 2. Use Array.FindAll<T> method
int[] b = Array.FindAll(a, element => element < 5);
Method 3. Use LINQ
int[] b = a.Where(element => element < 5).ToArray();
You could do something like this:
using System;
namespace exercices
{
class Hello
{
static void Main(string[] args)
{
int[] a = { 1, 2, 3, 4, 5, 6, };
int[] b = { };
for (int i = 0; i < a.Length;i++)
{
Int number=a[i];
if (number < 5)
b.Insert(i, number);
}
}
}
}
You can avoid explicit for loops using LINQ: the Where() method returns an IEnumerable object; you can then create an array or a list from the IEnumerable with the corresponding ToArray()/ToList() method, as shown below:
int[] a = { 1, 2, 3, 4, 5, 6};
IEnumerable<int> lessThanFiveElements = a.Where(element => element < 5);
int[] lessThanFiveArray = lessThanFiveElements.ToArray();
List<int> lessThanFiveList = lessThanFiveElements.ToList();
In case you have a console application, you can then print the resulting array/list with a Console.WriteLine() command, as shown below
Console.WriteLine(string.Join(",", lessThanFiveElements));
where I used the string.Join() in order to have comma separated elements, which accepts the separator as a first parameter and any IEnumerable as the second one.
Related
how do I pass an array with an unknown number of integers to a function?
Can anybody tell me what I am doing wrong?
I get the following error when trying to run the code:
Error CS1501 No overload for method 'Solution' takes 6 arguments
using System;
namespace IntegerTest
{
class Program
{
public static int Solution(int[] input)
{
Array.Sort(input);
int index = 0;
// Skip negatives
while (index < input.Length && input[index] < 1)
index++;
int expected = 1;
while (index < input.Length)
{
if (input[index] > expected)
return expected;
// Skip number and all duplicates
while (index < input.Length && input[index] == expected)
index++;
expected++;
}
return expected;
}
public static void Main()
{
Console.WriteLine(Solution( 1, 3, 6, 4, 1, 2));
}
}
}
You can either call the function with an array argument (e.g. Solution(new[] {1, 3, 6, 4, 1, 2}), or modify the function signature to take a params argument (int Solution(params int[] input)).
Your method accepts a int[], so create a new int[]
Solution(new int[] {1, 3, 6, 4, 1, 2});
You are passing 6 arguments to a method that takes one. Change your main method to something like this:
public static void Main()
{
int[] arr = { 1, 3, 6, 4, 1, 2};
Console.WriteLine(Solution(arr));
}
I want to convert int array to int so i can add them.
Example
int[] x = {1, 2, 3};
sum=x[0] + x[1] + x[2];
I have a loop for getting an input from user but i have to add all the values of every inputted.
Use the .Sum LINQ method:
var x = new int[] { 1, 2, 3 };
var sum = x.Sum(); // gives 6
Further info
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/
https://www.csharp-examples.net/linq-sum/
You can do this in a number of ways.
first by making a loop yourself.
static int Sum(int[] array)
{
int sum = 0;
foreach (var item in array)
{
sum += item;
}
return sum;
}
static void Main()
{
int[] x = new int[] { 1, 2, 3 };
Console.Write(Sum(x).ToString());
}
second, using the Sum() method in the System.Linq library
using System.Linq;
////
int[] x = new int[] { 1, 2, 3 };
Console.Write(x.Sum());
thank you USEFUL for feedback if it worked for you
It is not really clear what the problem is. Your code seems fully functional, so it is difficult to know what you are really trying to achieve and what the underlying issue it.
But certainly a simple loop would work fine.
int sum = 0;
for(int loop=0; loop < x.Length; loop++)
{
sum += x[loop];
}
You can also do this via Linq (I see somebody else posted that example, so I won't repeat it).
In my program, I have a function that finds the nearest index to an integer.
var indexWinnder = Array.IndexOf(scoreArray, nearestScore)
But the way that Array.IndexOf works is it finds the first match and uses that. I want a random index. Not the first. not the last. Is there any way I can do this?
There is no built-in method for that, but you could use your own method instead. My example uses a generic version of possible implementation.
class Program
{
static void Main(string[] args)
{
var arr = new int[] { 1, 2, 3, 1, 1, 5, 2, 6, 1 };
var randomIndex = RandomIndexOf(arr, 1);
Console.WriteLine(randomIndex);
Console.ReadKey();
}
static int RandomIndexOf<T>(ICollection<T> arr, T element)
{
var indexes = arr.Select((x, i) => new { Element = x, Index = i })
.Where(x => element.Equals(x.Element))
.Select(x => x.Index)
.ToList();
if (indexes.Count == 0) // there is no matching elements
{
return -1;
}
var rand = new Random();
var randomIndex = rand.Next(0, indexes.Count);
return indexes[randomIndex];
}
}
Maybe something like this is what you want:
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
int[] sampleArray = new int[] { 1, 2, 3, 2, 1, 3, 1, 2, 3 };
var indices = getAllIndices(sampleArray, i => i == 2);
var rnd = new Random();
var i = rnd.Next(0, indices.Count());
var randomIndex = indices.ElementAt(i);
Console.WriteLine(randomIndex);
Console.ReadLine();
}
static IEnumerable<int> getAllIndices(int[] array, Predicate<int> predicate)
{
for (var i = 0; i < array.Length; i++)
{
if (predicate(array[i]))
yield return i;
}
}
}
HTH
Update
Don't forget to check for empty arrays, null arguments etc.
I dont know if i understood your problem right but if u just want a random index you could write a method and use:
Random rnd = new Random();
int index = rnd.Next(MinValue, MaxValue); // e.g: MinValue: 0, MaxValue: Length of the Array
and then just use that index as the array index.
Random isnt the best option if u really want a random one because it follows a specific pattern that will occur again and again and again. If u want something even more Random you could look into
RNGCryptoServiceProvider: https://www.dotnetperls.com/rngcryptoserviceprovider.
Hope this helps!
This is my code, but everytime i try compiling it i keep getting this error:
System.IndexOutOfRangeException: Index was outside the bounds of the
array.
using System;
using System.Collections.Generic;
using System.IO;
namespace nrinfile
{
class Program
{
static void Main(string[] args)
{
List<int> numbers= new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
string[] folderLoc = File.ReadAllLines(#"E:\folder\numbers.txt");
for (int i = 0; i < 12; i++)
{
folderLoc[i] = Convert.ToString(numbers[i]);
}
}
}
}`
As you want to write from your list of numbers to a file, you will need to use a System.IO method which writes to a file.
Something like:
static void Main(string[] args)
{
string destFile = #"E:\folder\numbers.txt";
List<int> numbers = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
using (StreamWriter sw = new StreamWriter(destFile)) {
for (int i = 0; i < numbers.Count(); i++)
{
sw.WriteLine(numbers[i].ToString());
}
}
}
The using construct takes care of closing the file when the code has finished writing to it and disposing of any "unmanaged resources" that the StreamWriter used.
Instead of the using part and the code inside it, you could use a different method which takes an array of strings and writes that out as lines:
File.WriteAllLines(destFile, numbers.Select(n => n.ToString()).ToArray());
There's no guarantee that folderLoc has at least 12 items
for (int i = 0; i < 12; i++) {...}
You can put it like this (note folderLoc.Length instead of 12):
string[] folderLoc = File.ReadAllLines(#"E:\folder\numbers.txt");
// If you want at most 12 items to be changed put the condition as
// i < Math.Max(12, folderLoc.Length)
for (int i = 0; i < folderLoc.Length; i++)
{
folderLoc[i] = $"{i} {folderLoc[i]}"; //TODO: Apply the correct format here
}
Or even (no explicit loops, but Linq query)
using System.Linq;
...
string[] folderLoc = File
.ReadLines(#"E:\folder\numbers.txt")
.Select((value, index) => $"{index} {value}")
.ToArray();
If you want to change top 12 lines only, the Select should be
...
.Select((value, index) => index < 12 ? $"{index} {value}" : value)
...
Finally, if you want just to write 0..11 numbers into a file
File.WriteAllLines(#"E:\folder\numbers.txt", Enumerable.Range(0, 12));
This is my code, but clear method is not working, but I can't find the error.
This is the first time that clear method it's not working, anyone can help me?
using System;
using System.Collections.Generic;
public class test{
public static void Main()
{
try {
int[] myArr = {-1, 4, 8, 6};
PrintIndexAndValues(myArr);
Console.WriteLine();
Console.WriteLine("Taking index out of bound:");
Array.clear(myArr, 1, 2);
Console.WriteLine("Array After Operation:");
PrintIndexAndValues(myArr);
}
}
public static void PrintIndexAndValues(int[] myArr)
{
for (int i = 0; i < myArr.Length; i++) {
Console.WriteLine("{0}", myArr[i]);
}
}
}
From Arrays (C# Programming Guide):
The number of dimensions and the length of each dimension are established when the array instance is created. These values can't be changed during the lifetime of the instance.
If you want to be able to use Clear() the way you inted to, you should use a List instead:
List<int> myList = new List<int>{-1, 4, 8, 6};
// Do some stuff with your list
myList.Clear();
Edit:
Your PrintIndexAndValues actually only prints the values, here's how you could do it instead:
public static void PrintIndexAndValues(List<int> myList)
for (int i = 0; i < myList.Count; i++)
{
Console.WriteLine("{0}: {1}", i, myList[i]);
}
Edit2: Just realized that you probably wanted to remove the first and last element of the array, not clear the whole array?
This should do the trick:
myList.RemoveAt(3)
myList.RemoveAt(0)
The following is your corrected code
using System;
using System.Collections.Generic;
public class Test
{
public static void Main()
{
int[] myArr = {-1, 4, 8, 6};
PrintIndexAndValues(myArr);
Console.WriteLine();
Console.WriteLine("Taking index out of bound:");
Array.Clear(myArr, 0, myArr.Length);
Console.WriteLine("Array After Operation:");
PrintIndexAndValues(myArr);
}
public static void PrintIndexAndValues(int[] myArr)
{
for (int i = 0; i < myArr.Length; i++)
Console.WriteLine("{0}", myArr[i]);
}
}
This will set ALL values in your array to 0.