Split int array into two arrays [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
So I'm trying to split int array into two arrays that the difference of arrays sums would be minimum. Does anyone have any ideas how can I do that? Or any tips?
F.e.
int[] S = { 1, 1, 3, 6 };
We can split S array into
int[] a = {1,1,3};
and
int[] b = {6};
Array a sum is 5 and array b sum is 6 so the minimum difference is 1. By the way, I'm trying to get split arrays of S like a and b, not the sums difference.
Input:
int[] S = { 1, 1, 3, 6 };
Output: int[] a = {1,1,3}; and int[] b = {6};. That's what I'm trying to do.
So far I've tried Link
PROBLEM SOLVED! Thank you everyone for help!

The link you gave is for a more complex problem than the one you are showing us. In your example, elements can't be "reordered", so you can only subdivide the array in two parts. You simply have to choose where to "cut".
var array = new int[] { 1, 1, 3, 6 };
int leftSum = 0;
int rightSum = 0;
for (int i = 0; i < array.Length; i++)
{
rightSum += array[i];
}
int leftArraySize = 0;
int minDiff = rightSum;
for (int i = 0; i < array.Length; i++)
{
rightSum -= array[i];
leftSum += array[i];
int diff = Math.Abs(rightSum - leftSum);
if (diff < minDiff)
{
minDiff = diff;
leftArraySize = i + 1;
}
}
var leftArray = new int[leftArraySize];
var rightArray = new int[array.Length - leftArraySize];
Array.Copy(array, 0, leftArray, 0, leftArray.Length);
Array.Copy(array, leftArray.Length, rightArray, 0, rightArray.Length);
Simple code, without Linq: you have two "sum pools", leftSum and rightSum. You sum all the elements of the array in the rightSum pool. Then element by element you "move" one element from the rightSum sum to the leftSum sum. You then check if/when the difference between two "sum pools" is the minimum one. Then you simply copy the elements in two new arrays.

int[] values = new int[] { 1, 2, 3, 4, 5, 6 };
int minIndex = -1;
int minDiff = int.MaxValue;
for (int i = 0; i < values.Length; i++)
{
int p1 = 0;
for (int j = 0; j <= i; j++)
p1 += values[j];
int p2 = 0;
for (int k = i + 1; k < values.Length; k++)
p2 += values[k];
int diff = Math.Abs(p1 - p2);
if (diff < minDiff)
{
minIndex = i;
minDiff = diff;
}
}
Console.WriteLine("Min index = " + minIndex);
Console.WriteLine("Min difference = " + minDiff);

Related

"rotate" values in array clockwise

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;
}

C# jagged arrays [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
using System;
class TwoD
{
static void Main()
{
int[][,] a = new int[3][,];
a[0] = new int[2, 2];
// a[1] = new int[3, 3];
int i,j;
for (i = 0; i < 2; i++)
{
for (j = 0; j < 2; j++)
{
a[0][i,j] = i;//confused
}
}
for (i = 0; i < 2; i++)
{
for (j = 0; j < 2; j++)
{
Console.WriteLine(a[0][i, j] + " ");
Console.WriteLine();
}
}
This is the program and the output is
0
0
1
1
But i am little bit confused about initialisation of jagges array where i have commented. Please tell me the initialisation of jagged two dimentional array and correct me if i am wrong.
Not sure about where you are confused but I guess only confusion is about mixture of jagged array and multidimensional array. i.e. a[][] is jagged array, the second dimension can have any (or no) length. You have to initialize each dimension in a separate look While multidimensional array have same length for each dimension and that's why you can pre-initialize the multidimensional array. Like a[2,5].
Below example will explain more about initialization of each kind of array and how you can write more dynamic code of your example.
//jagged array sample of initialization
int[][] jagged = new int[3][];
for (int i = 0; i < jagged.Length; i++)
jagged[i] = new int[i + 4]; //each element of jagged array can have different length
//multidimensional array sample of initialization
int[,] multiD = new int[3, 4]; //that's it.
//multiD.GetLength(0) is 3 and multiD.GetLength(1) is 4
//Your example.
int[][,] a = new int[3][,];
a[0] = new int[2, 2];
a[1] = new int[3, 4];
int interationOrder = 0;
for (int jag = 0; jag < a.Length; jag++)
{
//considering rank of multidimentional array is always 2 (Rank of [,] = 2, Rank of [,,] = 3)
if (a[jag] == null)
continue;
for (int i = 0; i < a[jag].GetLength(0); i++)
{
for (int j = 0; j < a[jag].GetLength(1); j++)
{
a[jag][i, j] = interationOrder++;//no confusion :) this is corret.
}
}
}

C# program to sort a two dimensional array elements in ascending order?(sort the columns first and then the rows) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
public void ascendingOrder()
{
// helper class
double temp = 0;
for (int j = 0; j < numbers.Length; j++)
{
for (int i = 0; i < numbers.Length - 1; i++)
{
if (numbers[i] > numbers[i + 1])
{
temp = numbers[i];
numbers[i] = numbers[i + 1];
numbers[i + 1] = temp;
}
}
}
}
i need the code to sort the columns first and then sort the rows like the following example!
input :
n=3
2 2 1
3 53 4
32 5 3
output:
1 2 2
3 3 54
4 32 53
Some helpful links:
http://www.codeproject.com/Tips/166236/Sorting-a-Two-Dimensional-Array-in-Csharp
How to Sort 2D Array in C#
How do I sort a two-dimensional array in C#?
int[] array = new int[] { 3, 1, 4, 5, 2 };
Array.Sort<int>(array,
new Comparison<int>(
(i1, i2) => i1.CompareTo(i2)
));
Better way to sort array in descending order
I believe this person is currently writing an exam, so linq methods will not make him pass this test.
Try with this code.
double[,] numbers = new double[,]{ { 1, 3, 2 }, { 4, 6, 5 }, { 7, 9, 8 } };
// helper class
double temp = 0;
for (int k = 0; k < 3; k++)
{
for (int j = 0; j < 2; j++)
{
for (int i = 1; i < 3; i++)
{
if (numbers[k,i] < numbers[k,j])
{
temp = numbers[k,i];
numbers[k,i] = numbers[k,j];
numbers[k,j] =temp;
}
}
}
}

Display an integer array in a random order without using shuffle [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
int n;
Console.WriteLine("Please enter a positive integer for the array size"); // asking the user for the int n
n = Int32.Parse(Console.ReadLine());
int[] array = new int[n]; // declaring the array
int[] newarray = new int[n];
Random rand = new Random();
for (int i = 0; i < array.Length; i++)
{
array[i] = i + 1;
}
for (int y = 0; y < newarray.Length; y++)
{
int caseSwitch = 1;
switch (caseSwitch)
{
case 1:
newarray[y] = array[rand.Next(n)];
goto case 2;
case 2:
for (int z = y+1; z > 0; z--)
{
if (newarray[y] == newarray[z-1])
goto case 1;
}
break;
}
}
for (int x=0;x<newarray.Length;x++)
{
Console.Write(" {0}", newarray[x]);
}
Console.ReadLine();
This is the code i have started with but its not displaying any values, is it not filling the array? I'm new to this so any help would be much appreciated
I think your approach is extremely overly complicated for this. You should take a step back, think about what it is that you wish to accomplish, plan it out first, then start programming.
What you want to do is sort your array with a random sort order.
Create a new IComparer that returns the comparison randomly:
public class RandomComparer<T> : IComparer<T> {
private static Random random = new Random();
public int Compare(T a, T b) {
return random.Next(2) == 0 ? 1 : -1;
}
}
Now, sort your array:
int[] array = {
1, 2, 3, 4, 5,
6, 7, 8, 9, 10
};
Array.Sort<int>(array, new RandomComparer<int>());
for (int i = 0; i < array.Length; i++)
Console.WriteLine(array[i]);
It's really that simple. See this demonstration at IDEOne.com
It seems to get into an infinite loop. Try changing this bit:
case 2:
for (int z = y; z > 0; z--)
{
if (newarray[y] == newarray[z-1])
goto case 1;
}
break;
The reason you're not seeing any output is because the code isn't running to completion - it ends up bouncing between case 1 and 2 because
if (newarray[y] == newarray[z - 1])
is always true.
My recommendation would be to debug (i.e. step through) your code so you can really see why this is the case, then you'll be able to fix the code yourself :)
You can do it like this:
...
n = Int32.Parse(Console.ReadLine());
// Initial array filled with 1..n values
int[] data = Enumerable.Range(1, n).ToArray();
// data array indice to show, initially 0..n-1
List<int> indice = Enumerable.Range(0, n - 1).ToList();
Random gen = new Random();
for (int i = 0; i < n; ++i) {
if (i != 0)
Console.Write(' ');
index = gen.Next(indice.Count);
Console.Write(data[indice[index]]);
// Index has been shown, let's remove it since we're not going to show it again
indice.RemoveAt(index);
}
...
What you are trying to do is to generate a random permutation. You could try the following:
var rand = new Random();
var left = Enumerable.Range(1, n).ToList();
for(int i=0; i<n; ++i)
{
int j = rand.Next(n-i);
Console.Out.WriteLine(left[j]);
left[j].RemoveAt(j);
}
This is the simplest way to do it using a random comparison.
class Program
{
static Random rnd=new Random();
static void Main(string[] args)
{
int[] array= { 1, 2, 3, 4, 5, 6 };
int[] newarray=new int[array.Length];
array.CopyTo(newarray, 0);
Array.Sort(newarray, (i, j) => rnd.NextDouble()<0.5?-1:1);
// newarray is now randomly ordered
}
}
You can randomly switch the values :
int n;
Console.WriteLine("Please enter a positive integer for the array size"); // asking the user for the int n
n = Int32.Parse(Console.ReadLine());
int[] array = new int[n]; // declaring the array
int[] newarray = new int[n];
Random rand = new Random();
for (int i = 0; i < array.Length; i++)
{
array[i] = i + 1;
newarray[i] = i + 1;
}
for (int y = 0; y < newarray.Length; y++)
{
int r = rand.Next(n);
int tmp = newarray[y];
newarray[y] = newarray[r];
newarray[r] = tmp;
}
for (int x=0;x<newarray.Length;x++)
{
Console.Write(" {0}", newarray[x]);
}
Console.ReadLine();
use following code
int[] array = new int[n];
int[] randomPosition = new int[n];
Enumerable.Range(0, n ).ToList().ForEach(o => array[o] = o+1);
Random r = new Random();
Enumerable.Range(0, n).ToList().ForEach(o => randomPosition[o] = r.Next(0, n - 1));
foreach (var m in randomPosition)
{
var randomNumber = array[m];
//write randomnumber
}

Why are array indices repeating after an interval? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am trying to use selection sort in my code, and return the indexes of my array after sorting it, but my program is not giving the result as I want.
int kick=0;
int[] array = new int[10] { 100, 50, 20, 40, 10, 60, 80, 70, 90, 30 };
int[] index = new int[array.Length];
Console.WriteLine("The array before Selection Sort is: ");
for (int i = 0; i < array.Length; i++)
{
Console.WriteLine("array[" + i + "] = " + array[i]);
}
int tmp, min_key;
for (int j = 0; j < array.Length - 1; j++)
{
min_key = j;
for (int k = j+1 ; k < array.Length; k++)
{
if (array[k] < array[min_key])
{
min_key = k;
}
}
int min = min_key;
index[kick] = min;
tmp = array[min_key];
array[min_key] = array[j];
array[j] = tmp;
kick = kick + 1;
}
Console.WriteLine("The array index after Selection Sort is: ");
for (int i = 0; i < index.Length; i++)
{
Console.WriteLine("index[" + i + "] = " + index[i]);
}
Console.ReadLine();
The out put I am getting is
4
2
9
3
9
5
7
7
8
0
My question is why are indices repeating?
Why are 9 and 7 coming again? I don't want them again.
You can run and execute my code in console application.
The reason this does not work is that you are swapping the actual items, rather than swapping the indexes. The smallest item is initially at the index 4, then at index 2, then at index 9. At this point you swap 50 and 30, so 50 ends up at index 9. Then you find 40 item at index 3, and then you find 50 - again, at index 9. That's why the indexes repeat.
To fix this, change the algorithm to initialize index[i] = i for the entire range, and then change the algorithm to compare
array[index[k]] < array[index[min_key]]
Do not write to index at all (i.e. you do not need the kick index). Instead of swapping array[min_key] and array[j], swap index[min_key] and index[j]. This should take care of the problem: all items of the array would remain in place, only indexes would get sorted.
Do you really need the index instead of the sorted values? If you need the index, just swap it like you did with the values.
int kick = 0;
int[] array = new int[10] { 100, 50, 20, 40, 10, 60, 80, 70, 90, 30 };
int[] index = new int[array.Length];
for (int i = 0; i < index.Length; i++)
{
index[i] = i;
}
Console.WriteLine("The array before Selection Sort is: ");
for (int i = 0; i < array.Length; i++)
{
Console.WriteLine("array[" + i + "] = " + array[i]);
}
int tmp, min_key;
for (int j = 0; j < array.Length; j++)
{
min_key = j;
for (int k = j + 1; k < array.Length; k++)
{
if (array[k] < array[min_key])
{
min_key = k;
}
}
tmp = array[min_key];
array[min_key] = array[j];
array[j] = tmp;
tmp = index[min_key];
index[min_key] = index[j];
index[j] = tmp;
}
Console.WriteLine("The array index after Selection Sort is: ");
for (int i = 0; i < index.Length; i++)
{
Console.WriteLine("index[" + i + "] = " + index[i] + "(" + array[i] + ")");
}
Console.ReadLine();

Categories

Resources