Why are array indices repeating after an interval? [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 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();

Related

Trouble with multiplying array elements

Basically i'm trying to multiply each element of the first array with each element of the second array and then store it all at the end as a total. I'm pretty new to coding so just trying to learn and this one really has me stuck. This is the example of what it should eventually do.
ExampleArray1 = 5,6,7,8
ExampleArray2 = 2,3,4
(5*2)+(5*3)+(5*4) + (6*2)+(6*3)+(6*4) + (7*2)+(7*3)+(7*4) + (8*2)+(8*3)+(8*4) = 234
My code
int[] firstArray = { 5, 6, 7, 8 };
int[] secondArray = { 2, 3, 4 };
int[] thirdArray = new int[firstArray.Length * secondArray.Length];
for (int i = 0; i < firstArray.Length; i++)
for (int j = 0; j < secondArray.Length; j++)
{
thirdArray[i * firstArray.Length + j] = firstArray[i] * secondArray[j];
Console.WriteLine(thirdArray[i * firstArray.Length + j]);
}
You dont need a third array, you can just sum the results
var total = 0;
for (int i = 0; i < firstArray.Length; i++)
for (int j = 0; j < secondArray.Length; j++)
{
total += (firstArray[i] * secondArray[j]);
}
Console.WriteLine(total);
However you forgot to minus one form the length, in the third array index.
i.e to get the index you need i * (firstArray.Length - 1) + j
int[] thirdArray = new int[firstArray.Length * secondArray.Length];
for (int i = 0; i < firstArray.Length; i++)
for (int j = 0; j < secondArray.Length; j++)
{
thirdArray[i * (firstArray.Length - 1) + j] = firstArray[i] * secondArray[j];
}
Console.WriteLine(thirdArray.Sum());
You can apply some basic algebra to simplify this:
var total = 0;
var array1Total = 0;
var array2Total = 0;
for (int i = 0; i < firstArray.Length; i++)
{
array1Total += firstArray[i];
}
for (int j = 0; j < secondArray.Length; j++)
{
array2Total += secondArray[j];
}
total = array1Total * array2Total;
Console.WriteLine(total);
The reason is that if you expand (x0+x1+x2+x3...)*(y0+y1+y2+...) then you can see that you will multiply x0 by each of the y, then multiply x1 by each of the y, and so on. So you'll get each of the elements in the first brackets multiplied by each of the elements in the second brackets.
While this may not seem much different it will be considerably better for large arrays. if the length of your arrays are m and n then by the nested loops method you'll have m*n loop iterations. With the above technique you will have m+n. For small values this isn't a big deal. If you have arrays of thousands of items then the above will be significantly faster.
Of course, there is an even easier way to do the above:
var total = firstArray.Sum()*secondArray.Sum();

multiplying each element in array by all array elements, except itself

I need to make a loop that multiply each element in an array by all array elements, except itself .
Example ->
[1 3 4]
[1 3 4]
1 3, 1 4, 3 1, 3 4, 4 1, 4 3
I've wrote the following code:
foreach (int first in Array)
foreach (int second in Array)
Console.WriteLine(first + " " + second );
The code that I wrote multiplies every number with itself and the other elements.
any ideas on how to fix this?
Thanks
You should loop through the indices of the array instead of its elements. This way, you can check whether you are dealing with the same element by checking whether the two indices are equal:
var arr = new int[] {1, 3, 4};
var result = new List<string>();
for (int i = 0 ; i < arr.Length ; i++) {
for (int j = 0 ; j < arr.Length ; j++) {
if (i != j) {
result.Add($"{arr[i]} {arr[j]}");
}
}
}
Try nested for loops, with two indexes:
for (int ix1 = 0; ix1 < myArray.Length; ix1++) {
// Numbers before ix1.
for (int ix2 = 0; ix2 < ix1; ix2++) {
Console.WriteLine(myArray[ix1] + " " + myArray[ix2]);
}
// Numbers after ix1
for (int ix2 = ix1 + 1; ix2 < myArray.Length; ix2++) {
Console.WriteLine(myArray[ix1] + " " + myArray[ix2]);
}
}
I am more used to Java than C#, so best check my syntax for Javaisms.
Another approach that you can use:
int[] lst = new int[] { 2, 3, 4 };
int[] multipliedList = new int[lst.Length * (lst.Length - 1)];
int idx = 0;
for (int i = 0; i < lst.Length; i++)
{
int currIdx = 0;
foreach (var item in lst)
{
if (i != currIdx)
{
multipliedList[idx] = lst[i] * item;
idx++;
}
currIdx++;
}
}

Split int array into two arrays [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 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);

How to find duplicate element(1-10) in an array using console Application

How can I find duplicate element(1-10) in an array using console Application?
class program
{
static void Main(string[] args)
{
int[] array = { 10, 5, 8, 64, 25, 5, 5, 10, 10, 10};
int count = 1;
for (int i = 0; i < array.Length - 1; i++)
{
for (int j = i; j < array.Length; j++)
{
if(array[i] == array[j])
count = count + 1;
}
Console.WriteLine("\t\n " + array[i] + "occurs" + count);
Console.ReadKey();
}
}
}
The output is correct, but the loop is repeating.
From what I understand from your question, is seems like your loop is printing out how many duplicates each number has for each place in the array, instead of once for each unique digit.
One simple solution would be to create List<int> to keep track of the numbers you already checked for duplicates. The second for loop and Console.WriteLine part of the code will only execute if the number does not already exist in the List.
public static void Main(string[] args)
{
int[] array = { 10, 5, 8, 64, 25, 5, 5, 10, 10, 10};
List<int> doneNumbers = new List<int>();
for (int i = 0; i < array.Length - 1; i++)
{
if(!doneNumbers.Contains(array[i]))
{
int currentNumber = array[i];
int count = 0;
for (int j = i; j < array.Length; j++)
{
if(currentNumber == array[j])
{
count++;
}
}
Console.WriteLine("\t\n " + currentNumber + " occurs " + count + " times");
doneNumbers.Add(currentNumber);
}
}
}
Other things you also need to fix:
int count = 0 needs to be moved to inside the first for loop so that it resets for each element in the array.
int count should start from 0 instead of 1.
You do not need Console.ReadKey();.
Instead of constantly writing array[i], you should store that value in a variable and just reference that. I called currentNumber.

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

Categories

Resources