I have this situation:
int[] array = new int[] {7, 5, 6}
The value of my index i is 1 and it is pointing at the head of my hypothetical circular list. The value "7" at the zero position is the tail.
My aim is to print:
5,6,7
Do I need a specific structure or can I do it with a simple array?
With a single "for" loop and the modulo operator:
int[] array = new int[] {7, 5, 6};
int start = 1;
for (int idx=0; idx<array.Length; idx++)
Console.Write(array[(idx+start) % array.Length]);
There is nothing out of the box, but the following will wrap around the array.
int[] array = new int[] { 7, 5, 6 };
int startPosition = 1;
string result = "";
// Run from the start position to the end of the array
for (int i = startPosition; i < array.Length; i++)
{
result += array[i] + ",";
}
// Wrapping around, run from the beginning to the start position
for (int i = 0; i < startPosition; i++)
{
result += array[i] + ",";
}
// Output the results
result = result.TrimEnd(',');
Console.WriteLine(result);
Console.Read();
If you want to print 5,6,7 you could use:
int printIndex = 1;
for(int i = 0; i < array.Length; i++)
{
print(print(array[printIndex].ToString());
printIndex++;
if(printindex >= array.Length)
printindex = 0;
}
Related
I want to write a program which takes an array of size N, loop over it and sum all the numbers before i (including i itself). I haven't done a lot so far because I don't know how to access the indexs before i. When I try for example arr[i - 1], it throws me an error that the index was outside the array bounds.
int N = int.Parse(Console.ReadLine());
int[] arr = new int[N];
// Input
for (int i = 0; i < arr.Length; i++)
arr[i] = int.Parse(Console.ReadLine());
// Here we need to sum
for (int i = 0; i < arr.Length; i++)
//
Example (N = 4)
Before = [1, 2, 3, 4]
After = [1, 3, 6, 10]
I don't know if this helps your learning process, but this is what I would do if I needed to do that logic.
Use Range to generate a collection of consecutive integers, up to n, then do a projection with LINQ of another collection from 1 to each value, then sum and convert to array.
int n = 10;
var result = Enumerable.Range(1, n)
.Select(e => Enumerable.Range(1, e).Sum()).ToArray();
You can initialize the result array with the correct size beforehand and then use a plain loop to calculate the "running sum". You need a variable to track the current value:
int[] result = new int[arr.Length];
int currentSum = 0;
for (int i = 0; i < arr.Length; i++)
{
currentSum += arr[i];
result[i] = currentSum;
}
For example i've got one array like
int[] array = {1,0,0,1,0}
and one int variable=0;
I want set all array's elements into variable. How can i do this?
variable=10010
In addition if we think about reverse of this situation? Variable's values set to array?
int something=10000 to int[] something={1,0,0,0,0}
Thanks for your all contribution
//==============go forwards===================
int[] array = { 1, 0, 0, 1, 0 };
int variable = 0;
for (int i = 0; i < array.Length; ++i)
{
//first element
if (i == 0)
variable = array[i];
else
{
variable *= 10;
variable += array[i];
}
}
//print resualts
Console.WriteLine(variable);
//===================go backwards===============
int variable2 = 10010;
//convert it into a char array
string value = variable2+"";
//set the array length based on the size
int[] reverse = new int[value.Length];
//loop
for (int i = 0; i < value.Length; ++i)
{
//grab the number from a char value and push it into the array
reverse[i] = (int)Char.GetNumericValue(value[i]);
}
//print out
for(int i = 0; i <reverse.Length;++i)
{
Console.WriteLine("[" + i + "] = " + reverse[i]);
}
Yet another way to do this, but not as compact as others. This approach demonstrates bit-wise operations to construct an int from the array of 0's and 1's.
class Program
{
// converts array of 0's and 1's to an int, and assumes big endian format.
static int bitArrayToInt(int[] bit_array)
{
int rc = 0;
for (int i = 0; i < bit_array.Length; i++)
{
rc <<= 1; // bit shift left
rc |= bit_array[i]; // set LSB according to arr[i].
}
return rc;
}
static void Main(string[] args)
{
int[] array = { 1, 0, 0, 1, 0 };
int rc = bitArrayToInt(array);
System.Console.WriteLine("{0} = {1} binary",rc, Convert.ToString(rc, 2));
System.Console.ReadLine();
}
}
There's a huge number of choices on how to approach the problem.
Shortest quickest method I could think of.
byte[] array = { 1, 0, 1, 0, 0 };
string temp = "";
int result = 0;
for (int i = 0; i < array.Length; i++)
temp += array[i].ToString();
result = Convert.ToInt32(temp);
I'm on my phone here, so bear with me, but if performance isn't an issue then how about something like:
int.Parse(string.Join(string.Empty, array.Select(d => d.ToString()));
Obviously you'll need some error handling around the parsing for overflows, invalid characters, etc.
Firstly thank you for taking the time to look at my question.
I have a csv file of letters for which i need to get the last letter of the array and move it to the start while "pushing" the other letters across
E.G.
--Source--
a,b,c,d,[e]
--Rotated--
e,a,b,c,d
for (var i = 0; i < Array.Length - 1; i++)
{
temp = Array[Array.Length];
Array[Array.Length] = Array[Array.Length - 1];
Array[i + 1] = Array[i];
Array[i] = temp;
}
For this I am aware that not all characters would be effected but i cant think of a loop to get all values moved
Use Copy method:
int last = arr[arr.Length - 1];
Array.Copy(arr, 0, arr, 1, arr.Length - 1);
arr[0] = last;
You can shift the numbers to right by using the modulo % operator :
int[] arr = { 1, 2, 3, 4, 5 };
int[] newArr = new int[arr.Length];
for (int i = 0; i < arr.Length; i++)
{
newArr[(i + 1) % newArr.Length] = arr[i];
}
newArr = {5,1,2,3,4}
DEMO HERE
EDIT:
Or you could make a method that shifts the numbers in your initial array without the need for creating a new array. The method rightShiftArray takes two parameters, the initial array arr an the number of shifts (shift) you want to perform:
public void rightShiftArray(ref int[] arr, int shift)
{
for (int i = 0; i < shift; i++)
{
int temp;
for (int j = 0; j < arr.Length - 1; j++)
{
temp = arr[j];
arr[j] = arr[arr.Length - 1];
arr[arr.Length - 1] = temp;
}
}
}
For example:
int[] arr = { 1, 2, 3, 4, 5 };
rightShiftArray(ref arr, 2);
The code above shifts the numbers in the initial array arr twice to the right and gives you the following output:
arr = { 4, 5, 1, 2, 3};
DEMO HERE
if you doesn't want to allocate new array, you can use this code :
newValue = Array[Array.Length-1];
for (var i = 0; i < Array.Length; i++)
{
temp = Array[i];
Array[i] = newValue;
newValue = temp;
}
I Have an array, TempArray[] = {1,3,-1,5,7,-1,4,10,9,-1}
I want to remove every single -1 from this array and copy the remaining arrays into a new array called Original, which should output the numbers as 1,3,5,7,4,10,9
I can only use an if statement within a for loop!
This is what I have so far, but I keep getting an error message, System.IndexOutOfRangeException
for (int i = 0; i < TempArray.Length; i++)
{
if (TempArray[i] != -1)
{
//error occurs at this line
//My attempt is to set the new array, Original[i] equal to TempArray[i] only where the values are not -1.
TempArray[i] = Original[i];
}
}
If you can only use If statement in for loop. This looks like a school project. First you count how many non negative numbers are there in your array. Create new array with that length and fill that array.
int[] TempArray = new int[] {1,3,-1,5,7,-1,4,10,9,-1};
int[] Original ;
int countNonNegative=0;
for (int i = 0; i < TempArray.Length; i++)
{
if (TempArray[i] != -1)
{
countNonNegative++;
}
}
Original = new int[countNonNegative];
int index=0;
for (int i = 0; i < TempArray.Length; i++)
{
if (TempArray[i] != -1)
{
Original[index] = TempArray[i];
index++;
}
}
Console.WriteLine("Original Length = "+Original.Length);
using System.Linq;
int[] withoutNegativeOnes = myArray
.Where(a => a != -1)
.ToArray();
var Original = new int[TempArray.Length];
var originalCounter = 0;
for (int i = 0; i < TempArray.Length; i++)
{
if (TempArray[i] != -1)
{
Original[originalCounter++] = TempArray[i];
}
}
Now Original may contain empty spaces at the end though, but you have all the elements which aren't -1. You can use the following code to iterate through the values:
for (int i = 0; i < originalCounter; i++)
{
Console.WriteLine(Original[i]);
}
and that's because the originalCounter has the last index values that wasn't filled from TempArray's iteration.
try this one
int[] TempArray = { 1, 3, -1, 5, 7, -1, 4, 10, 9, -1 };
int[] original = TempArray.Where(i => i != -1).ToArray();
foreach(int i in original)
Console.WriteLine(i.ToString());
Can't figure out why the line winningNumbers[i] += count; comes up as outside the bounds of the array.
static int[] CheckWinningNumbers(int[][]lottoNumbers, int[]drawNumbers)
{
int[] winningNumbers = new int[8];
for (int i = 0; i < lottoNumbers.Length; i++)
{
int k = 0;
int count = 0;
for (int j = 0; j < lottoNumbers[i].Length; j++)
{
if (lottoNumbers[i][j] == drawNumbers[k])
{
count +=1;
}
k += 1;
winningNumbers[i] += count;
}
}
return winningNumbers;
Just replace
int[] winningNumbers = new int[8];
With
int[] winningNumbers = new int[lottoNumbers.Length];
As long as you are iterating lottoNumbers.Length the variable i will not exceed its boundaries.
Edit
I ran it with the following data and it works
int[][] lottoNumbers = { new[] { 1, 2 },
new[]{ 3, 4 },
new[]{ 5, 6 },
new[]{ 7, 8 } };
int[] drawNumbers = {1, 4, 5, 8};
I don't know what data you are testing it on but you are using jagged arrays intead of multidimensional. this will not guarantee that all your sub arrays have the same length which might be problematic. If all the arrays have the same length and performance is not critical here I'd suggest you use Multidimensional Arrays