C# can't use the "Length" function [duplicate] - c#

This question already has answers here:
All possible array initialization syntaxes
(19 answers)
Closed 2 years ago.
I am now learning how to use the For Loops in C#, but when I try to compile my program, three errors in the console appear and one of them says that int doesn't have a definition for Lenght (I'm just not showing the errors because they are in portuguese), any idea about why this is happening?
using System;
namespace Giraffe
{
class Program
{
static void Main(string[] args)
{
int luckyNumbers = {4, 8, 15, 16, 23, 42};
for (int i = 0; i < luckyNumbers.Length; i++)
{
Console.WriteLine(luckyNumbers[i]);
}
Console.ReadLine();
}
}
}

You have an incorrect array declaration, change it to
int[] luckyNumbers = {4, 8, 15, 16, 23, 42};
You current declaration int luckyNumbers = {4, 8, 15, 16, 23, 42}; is invalid, you can't assign an array instance to int variable, therefore Length property isn't available

Related

Fast Sequence checking in a List<int> [duplicate]

This question already has answers here:
Is there a built-in method to compare collections?
(15 answers)
Functional way to check if array of numbers is sequential
(7 answers)
Closed 4 years ago.
I am looking for a faster and more accurate way to check a Sequence:
List<int> sequence = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7 … 41}
private bool IsSequential(List<int> sequence)
{
int S = sequence[0];
int T = sequence[sequence.Count- 1];
List<int> Possible = Enumerable.Range(S, T).ToList();
List<int> Except = sequence.Except(Possible).ToList();
if (Except.Count == 0)
return true;
else
return false;
}
My code returns 1 if the list is the same, I have some sort of count issue?
I wonder if there is a better way to check an integer sequence: 200, 201, 202... and so on.
Some Sequences may be out of sequence: 200, 210, 203, 204... I need to identify this issue.
Thanks
You can try like following using SequenceEqual.
List<int> sequence = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7 };
bool isInSequence = sequence.SequenceEqual(Enumerable.Range(sequence[0], sequence.Count()));

How can I find the closest number to int x, among all the values in an int array? [duplicate]

This question already has answers here:
finding closest value in an array
(6 answers)
Closed 6 years ago.
I've recently started learning C# and now I am making a Windows Form Application.
First I have an array of int here:
int[] myArray = new int[] {1, 2, 3, 4, 5, 6, 7};
and also, I want to read the value (int) that user entered.
Here I declare it as below.
int userInput = Textbox.Text;
What I want to do with these two things is, among the values in myArray, I want to find out the closest one to the value of userInput.
And I want to store the closest number in another array, because I will repeat the this same action for several times and analyze which number came up most often.
I apologize for my unclear explanation, I'm still learning English.
Thank you!
int usernumber = 3; //Get input from textbox
int[] myArray = new int[] { 1, 2, 3, 4, 5, 6, 7 };
var nearest = myArray.OrderBy(x => Math.Abs((long)x - usernumber)).First();

StackoverflowException when filling array

I usually spend my time reading and trying to answer the Excel VBA questions but I am trying to learn C# now. Can someone help me understand why I get a StackOverflowException error on the second to last line in my code?
I am trying to fill an array via a method.
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int[] numbers = GenerateNumbers();
Console.WriteLine(numbers);
Console.ReadKey();
}
static int[] GenerateNumbers()
{
int[] num = new int[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
return GenerateNumbers();
}
}
}
You are confusing the weird VBA way of returning functions with C#. You are returning an infinite recursion, which can be easily fixed by using this:
static int[] GenerateNumbers()
{
int[] num = new int[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
return num; //you don't return the function name but a variable
}
A stack overflow is an undesirable condition in which a particular
computer program tries to use more memory space than the call stack
has available. In programming, the call stack is a buffer that stores
requests that need to be handled. http://whatis.techtarget.com/definition/stack-overflow
static int[] GenerateNumbers()
{
int[] num = new int[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
return GenerateNumbers(); //Here is where the problem happens
}
The problem lies with the return part. You are calling the same function in the same function creating a stack of the same function again and again and... You get the picture.
Change it to
return num;
By calling return GenerateNumbers() at the end of your function, you are running that function over and over again infinitely because there is no way to break the recursion, causing the stack overflow. You should instead use return num
This is what you're esentially doing:
void Main()
{
FlipPage();
}
void FlipPage()
{
FlipPage();
}
So like that blond you keep flipping that page in all eternity

C# array of references without unsafe

I found similar topics, but I could not solve the problem I has reading them.
I want to do in C# the same thing like in C is array of pointers, but I do not want to use in C# pointers because it requires to use "unsafe".
How to build an array of " ref to int" that when I change any element of that array then I will also change that what it refs to at the same time the variable that it points to ( Like in C - array of pointers).
Best regards,
Chris
If performance is not a concern, than one common workaround is to use lambda to capture the access to value type variable:
Sample:
class GetSetPair<T>
{
public Func<T> Get {get;set;}
public Action<T> Set {get;set;}
}
var referencesToInt = new List<GetSetPair<int>>();
int value = 42;
referencesToInt.Add(new GetSetPair<int>{Get=()=>value, Set = v => value = v});
referencesToInt[0].Set(33);
Console.WriteLine(value); // 33
value = 22;
Console.WriteLine(referencesToInt[0].Get()); //22
Arrays are reference types, and therefore you can pass around references to that array. For example, given the following program:
public class Program
{
public static Random rnd = new Random();
public static int[] array2;
public static void Main()
{
int[] array = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
PrintArray(array);
array[4] = rnd.Next();
PrintArray(array);
ModArray(array, 2);
PrintArray(array);
array2 = array; //This makes array2 reference array1
ModArray(array2, 8); //Operate on the array2 reference
PrintArray(array); //Changes are reflected in array
PrintArray(array2); //And in array2
Console.ReadKey(true);
}
public static void PrintArray(int[] array)
{
foreach (var e in array)
Console.Write(e + ", ");
Console.WriteLine();
}
public static void ModArray(int[] array, int i)
{
array[i] = rnd.Next();
}
}
Will give the following output:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, <- Original
1, 2, 3, 4, 744477516, 6, 7, 8, 9, 10, <- Modified in Main
1, 2, 102109069, 4, 744477516, 6, 7, 8, 9, 10, <- Modified in ModArray
1, 2, 102109069, 4, 744477516, 6, 7, 8, 1776657318, 10, <- array, after modifying array2
1, 2, 102109069, 4, 744477516, 6, 7, 8, 1776657318, 10, <- array2
So in a sense, you can pass around a reference to the array, modify that reference, and have it reflected in all of its copies.
The caveat here is that anybody who "owns" a reference to the original array cannot reassign that array (or resize it). It can modify the elements of the array, but it can't make the original array point to a new instance (which is what happens when it is resized). Also, as Jon Skeet mentioned in his comment, the danger is that if you were doing this in a different method other than Main, if the array goes out of scope, what would happen to array2?
See Also:
Is int[] a reference type or a value type?
Are arrays or lists passed by default by reference in c#?

Please help, now I have a matrix, I want use Combination algorithm to generate a array for length 6

The first thanks a lot for your help , the following is my matrix, I want to implement combination algorithm between multiple arrays in LINQ for this matrix.
int[,] cj = {
{ 10, 23, 16, 20 },
{ 22, 13, 1, 33 },
{ 7, 19, 31, 12 },
{ 30, 14, 21, 4 },
{ 2, 29, 32, 6 },
{ 18, 26, 17, 8 },
{ 25, 11, 5, 28 },
{ 24, 3, 15, 27 }
};
other:
public static IEnumerable<IEnumerable<T>> Combinations<T>(this IEnumerable<T> elements, int k)
{
return k == 0 ? new[] { new T[0] } :
elements.SelectMany((e, i) =>
elements.Skip(i + 1).**Combinations**(k - 1).Select(c => (new[] { e }).Concat(c)));
}
The above method has a error in my project, System.Collections.Generic.IEnumerable' does not contain a definition for 'Combinations' and no extension method 'Combinations' accepting a first argument of type 'System.Collections.Generic.IEnumerable' could be found (are you missing a using directive or an assembly reference?
I use .Net Framework3.5, what is the reason it?
The error you have is actually a compiler error and should be claimed at the line you try invoking your extension method. Have you made sure you extension method is declared in a static class and it's namespace has been imported?
I see you are recursively invoking your extension method, but I can compile your code just fine. The error should be at another callsite.

Categories