How can we get the middle element in an array?
Example code:
string[] source = txtInput.Text.Split(',');
int[] nums = new int[input.Length];
for (int i = 0; i < source.Length; i++)
{
nums[i] = Convert.ToInt32(source[i]);
}
int first=nums[0];
int mid=///how is it?
Like this:
int mid = nums[nums.Length/2];
You take the size of the array (nums.Length), divide by two to get the index in the middle and use that index.
int mid = nums[nums.Length / 2];
Since it is all ints the number will be rounded down if Length is odd.
mid = input.Lenght/2
Get the middle index and then return the element at that middle index:
int [] arr = {1,2,3,4,5,6,7}
int middIndex = arr.Length / 2;
Console.WriteLine(arr[middIndex]);
the total number of elements devided by 2 gives the middle element:
int mid = nums[Convert.ToInt32(num.Count /2)];
Related
I'm looking for a way to replace every int that is greater than 9 in an array with the sum of the digits. I'm gonna demonstrate an example below.
I have this array:
int[] ints2 = new int[] { ints[0] * 2, ints[1], ints[2] * 2, ints[3], ints[4] * 2, ints[5], ints[6] * 2, ints[7], ints[8] * 2, ints[9]};
And I want to replace the first int to whatever the sum is of the two digits.
Lets say ints[0] = 9. And ints[0]*2 = 18. The sum should be 1+8 = 9.
Can I use some kind of replace method for ints? Or do you guys have any better ideas of how to deal with this issue?
I tried it like this, but obviously I'm wrong:
foreach (int number in ints)
{
int newNumberInt;
if (number > 9)
{
string newNum = number.ToString();
char[] charNum = newNum.ToCharArray();
int[] intNum = Array.ConvertAll(charNum, n => (int)Char.GetNumericValue(n));
newNumberInt = intNum[0] + intNum[1];
}
newNumberInt = number;
}
You are close. Your mistakes are an incorrect addition of digits, and failure to replace the values in the array. Here is a one line method that adds all the digits in an integer (using System.Linq):
//Adds up all the digits in a number
private static int AddDigits(int number) => number.ToString().Sum(digitCharacter => int.Parse(digitCharacter.ToString()));
For replacing the values, a foreach loop directly on the array won't work, due to changing the contents of the array during enumeration. A simple solution is to use a for loop.
for (int i = 0; i < ints.Length; i++)
{
var value = ints[i];
ints[i] = value > 9 ? AddDigits(value) : value;
}
Note: the AddDigits function I wrote only works for positive integers
My array max size is 20. If I were to enter data that would be less than 20,how do I get it where my program only counts the used arrays?
for (int i = 0; i < Score.Length; i++)
{
sum = sum + Score[i];
}
average = sum / Score.Length;
If I use this for loop above, it always divides by 20 for the average. I need it to only count the ones I entered, not 20. I would prefer solutions using arrays
If you insist in using arrays, then you must keep track of how many items you added to the array, like:
int[] Score = new int[20];
Random rdn = new Random();
int size=0;
for(int i=0;i<rdn.Next(0,20);i++)
{
Score[i] = rdn.Next();
size++;
}
int sum = 0;
for (int i = 0; i < size; i++)
{
sum = sum + Score[i];
}
double average = sum / size;
A better option is to use the List class that keep track for you of the number of items you add
List<int> Score = new List<int>();
Random rdn = new Random();
for(int i=0;i<rdn.Next(0,20);i++)
{
Score.Add(rdn.Next());
}
int sum = 0;
for (int i = 0; i < Score.Count; i++)
{
sum = sum + Score[i];
}
double average = sum / Score.Count;
And of course, as you didn't say the type of your data you could use other data types, like double, float, long, decimal for both solutions.
That is probably an overkill, but another approach would be to use a SparseVector class of the Math.Numerics package:
Sparse Vector uses two arrays which are usually much shorter than the vector. One array stores all values that are not zero, the other stores their indices.
PM > Install-Package MathNet.Numerics
var vector = SparseVector.Build.SparseOfArray(Score);
var sum = vector.Sum();
Sum() will only go through non-empty elements.
You need to keep track of the record that are != 0, so
int count = 0;
for(int i = 0; i < array.Length; i++)
{
if ( array[i] != 0 )
{
count++;
sum += array[i];
}
}
average = sum / count;
And beware of division by 0 ;)
I`m facing with the problem of putting char in random position.
I have a table full of dots and I have to replace 30% of these dots with *
Size: 10x5
I used function Random.
Random rnd = new Random();
if (rnd.Next() % 10 > 3)
Console.Write(". ");
else
Console.Write("* ");
Everything is in 2 loops which hold Length and Height of table (10x5).
But it only makes PROBABILITY of 30% to make * instead of .
It takes good position but every time I start a program there is different amount of *.
It should just have 16 of * (17 - if rounded) every time I start the program
How should I suppose to make 30% always instead of probability?
You have 50 dots. calculate 50*30/100, it becomes 15.
Then generate 15 unique random numbers within range of 0 to 50. those numbers are indexes you have to replace . with *
var indexes = Enumerable.Range(0,50).OrderBy(x => rng.Next()).Take(50*30/100).ToList();
If you are working with 2d index, its fairly easy to convert 1d index into 2d index.
var i = index % 5;
var j = index / 5;
According to what #KonradRudolph said if you don't want to use OrderBy you can check out other ways to shuffle array (or create randomized set) posted here Best way to randomize an array with .NET
Here is more efficient way using Fisher-Yates algorithm that I suggest you to use instead of using OrderBy
var indexes = Enumerable.Range(0, 50).ToArray();
RandomExtensions.Shuffle(rng, indexes);
Write code that does the following:
Declare an array with x * y elements
Populate the entire array with .
Declare a loop with 0.30 * x * y iterations
For each iteration, change a randomly selected element from . to * (you must keep looking until you find one that isn't already a *)
Output the array, x elements per line
Imagine your array to be just 50 elements and forget about the rectangular shape for now. How would you approach that? Declare X dots and 50-X stars, then randomly order them. Like you would randomly order a 1->50 list of numbers.
Now how to randomly order a list of 1->50 numbers? One simple and intuitive way is imagining shuffling cards. Go through the loop and for each position obtain a random number in 1->50. Swap elements chosen (say for i=1 we got random number 7 => swap elements 1 and 7).
Here, you simply need to map this rectangle to those 50 points, which is trivial enough for 2D.
I would randomly select 30% of the possible positions
// create char array
int arrayRows = 5;
int arrayCols = 10;
char[,] arr= new char[arrayRows ,arrayCols];
// populate array with dots
for (int i = 0; i < arrayRows; i++)
{
for (int j = 0; j < arrayCols; j++)
{
arr[i,j] = '.';
}
}
Random rnd = new Random();
int numberOfPossiblePositions = arrayRows * arrayCols;
int k = 0;
while (k < numberOfPossiblePositions * 0.3) {
int position = rnd.Next(numberOfPossiblePositions);
int colIndex = position / 10;
int rowIndex = position % 10;
// if the cell already has * try again
if (arr[rowIndex,colIndex] == '*') {
continue;
}
arr[rowIndex,colIndex] = '*';
k++;
}
Create an array that holds x*y/3 starts and the rest are dots. order by random and iterate through it.
This is the array:
Enumerable.Range(0, count).Select(i => new {Text = "*", Order = rnd.Next() })
.Concat(Enumerable.Range(0, x*y - count)
.Select(i=>new { Text = ".", Order = rnd.Next() }))
.OrderBy(i => i.Order).Select(i=>i.Text).ToList();
And this is the code for iteration:
Random rnd = new Random();
int x = 10;
int y = 5;
int count = x*y/3;
var allPlaces =
Enumerable.Range(0, count).Select(i => new {Text = "*", Order = rnd.Next() })
.Concat(Enumerable.Range(0, x*y - count)
.Select(i=>new { Text = ".", Order = rnd.Next() }))
.OrderBy(i => i.Order).Select(i=>i.Text).ToList();
for (var i = 0; i < x; x++)
{
for (var j = 0; j < y; j++) { Console.Write(allPlaces[i*j + j]); }
Console.WriteLine();
}
I am trying to insert an int value in int array at the user input index and getting an error: Index was outside the bounds of the array. The error is in the while loop, but the solution does not use any methods like Array.Add etc.
Console.WriteLine("Enter the length of Linear Array");
int length = Convert.ToInt32(Console.ReadLine());
int[] LinearArr = new int[length];
Console.WriteLine("Maximum number of input : {0}",length);
for (int i = 0; i < LinearArr.Length; i++)
{
LinearArr[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("What number you want to insert and at what index");
int InsertNum = Convert.ToInt32(Console.ReadLine());
int k = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Number :{0} and Index :{1}",InsertNum,k);
while (length>=k)
{
LinearArr[length + 1] = LinearArr[length];
length = length - 1;
}
LinearArr[k] = InsertNum;
length = length + 1;
Console.ReadLine();
Change your while loop condition from:
while (length >= k)
to:
while (length > k)
as in current condition it will access last index which is not in the array.
Another mistake is your array is of size of value in the length variable:
LinearArr[length]
and in while loop you are accessing index greater then array length:
LinearArr[length + 1] = LinearArr[length]; // length +1 will give out of bounds error
When you define
int[] LinearArr = new int[length];
the valid indexes are 0..length-1. Therefore, this expression causes an out-of-range exception:
LinearArr[length + 1] = LinearArr[length];
neither length nor length+1 are valid indexes.
In order to fix this problem, allocate enough space in the array, and start moving elements at length-1:
int[] LinearArr = new int[length+1]; // Make space for an expansion
...
while (length > k) {
LinearArr[length] = LinearArr[length-1];
length--;
}
You may want to consider using a List<int> instead of an int[] as it provides an Insert function.
Is it possible to convert a HEX string to an integer array?
// This string...
string a = "8FCC44";
// Should look like this:
int[] b = {0x8f,0xcc,0x44};
But I don't have any idea how to do this.
I found this question, but i can't understand the answer. I am new to C#, so it would be nice if anybody could give me an example.
Thanks in advance!
int[] ConvertToIntArray(string a)
{
List<int> x = new List<int>();
for(int i=0; i<a.Length-1; i+=2)
x.Add(int.Parse(a.Substring(i, 2), System.Globalization.NumberStyles.HexNumber));
return x.ToArray();
}
You can then print them as Hex or Decimal using ToString() overloads of int (Int32) class.
Another way:
var a = "8fcc44";
var b = Enumerable.Range(0, a.Length / 2).Select(x =>
Convert.ToInt32(a.Substring(x * 2, 2), 16)).ToArray();
The answer focuses on Java, but it is also possible to do this in C# in a similar way. Basicly you have to divide the string into substrings, each 2 characters long:
"8FCC44" -> "8F", "CC", "44"
You can do this using a for loop:
for (int i = 0; i < a.Length; i += 2)
The loop variable i represents the start index of the current substring, this is why it always increases by 2. We can convert each substring using Int32.Parse:
Convert.ToInt32(a.Substring(i, 2), 16);
The last parameter represents the base of the source string (HEX = base 16).
Now we need an array to store the results. The size of the array can be calculated by the length of the string, divided by the length of each substring (= 2):
int[] b = new int[a.Length / 2];
To bring it all together your code could look like this:
string a = "8FCC44";
int[] b = new int[a.Length / 2];
for (int i = 0, int j = 0; i < a.Length; i += 2, j++)
b[j] = Convert.ToInt32(a.Substring(i, 2), 16);
Hope this helps!
static void Main(string[] args)
{
string a = "8fcc44";
int itemNumber = 0;
int[] iArray = new int[3];
for (int i = 0; i < a.Length - 1; i += 2)
{
iArray[itemNumber] = (int.Parse(a.Substring(i, 2), System.Globalization.NumberStyles.HexNumber));
itemNumber++;
}
}