I would like to ask how to minus some value from all values in an array c#?
List<int> array = new List<int>();
array.Add(4,5,3)
array minus 1;
for (int z = 0; z < N; z++)
{
Console.WriteLine(array[z]);
}
Console.ReadLine();
In output I would like to have this: 3,4,2
Actually I would like to do it in a way that I can work with the changed array not just to print out array minus 1.
I would like to rename the variable first, a list of integers with a name array is not good. so let me call the variable as ListInt. instead of using -1 it is better to use a variable called someValue. now see the code and how it works:
List<int> ListInt = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int someValue = -1;
ListInt = ListInt.Select(x => x - someValue).ToList();
// now the ListInt contains all the values as required
// Print the values using
Console.WriteLine(String.Join(",",ListInt));
Multiple approaches:
a plain foreach-loop:
foreach(int i in array)
Console.WriteLine(i - 1);
a for-loop:
for(int i = 0; i < array.Count; i++)
Console.WriteLine(array[i] - 1);
List.ForEach:
array.ForEach(i => Console.WriteLine(i - 1));
LINQ:
var arrayMinusOne = array.Select(i => i - 1);
foreach(int i in arrayMinusOne)
Console.WriteLine(i);
You can use this arrayMinusOne query multiple times (but note that it will be executed every time you use it). Or you could create a new collection with arrayMinusOne.ToList() or ToArray. If you want to modify the original list you can use the for-loop:
for (int i = 0; i < array.Count; i++)
array[i] = array[i] - 1;
or reassign arrayMinusOne.ToList() to the array variable. Note that a list is not an array.
Following your style to help you understand, this will display what you want:
for (int z = 0; z < array.Length; z++)
Console.WriteLine(array[z]-1);
But this will actually subtract 1 from the data before displaying the resulted data:
for (int z = 0; z < array.Length; z++)
array[z]--;
for (int z = 0; z < array.Length; z++)
Console.WriteLine(array[z]);
This code is in VB.Net, but have the logic:
Dim array As New List(Of Integer)()
array.Add(4)
array.Add(5)
array.Add(3)
Dim resta = -1
For index = 0 To array.Count - 1
array(index) = array(index) - 1
Console.WriteLine(array(index))
Next
Console.ReadLine()
List<int> array = new List<int>();
array.Add(2);
array.Add(3);
array.Add(4);
for (int z = 0; z < array.Count; z++)
{
array[z] = array[z] - 1;
}
Console.WriteLine(array[0]);
Console.ReadLine();
Linq solution:
List<int> array = new List<int>() {
4, 5, 3,
};
// "3, 4, 2"
Console.Write(String.Join(", ", array.Select(item => item - 1)));
Console.ReadLine();
In case you want to put each item on the separate line
// 3
// 4
// 2
Console.Write(String.Join(Environment.NewLine, array.Select(item => item - 1)));
Related
Let's Say We Have an Array Of Int :
int[] array = new int[5];
and inside of this array we have a 5 randomly numbers..
array = {10,5,7,0,3};
What Would be The Best Way To Change That array To This Array By Code
array[0]=0;
array[1]=3;
array[2]=5;
array[3]=7;
array[4]=10;
For Me i Thought about Creating Two Loops One Of i and One of j..
im gonna take the position 0 (i) and compare it with All the Other Numbers in The Array. i mean The positions j which is started from (i+1) till the end of the array (array.Length).
Then When i'll found that array[i] is Upper Than array[j] Simply i'll Change The first Value with The Other...
and Of course Here i need To Declare variable To Make That Change as shown :
int[] array = new int[5]{10,5,7,0,3};
int Change;
for(int i =0;i<array.Lenght;i++)
{
for(int j =i+1;j<array.Lenght;j++)
{
if(array[i]>array[j])
{
change=array[i];
array[i] = array[j];
array[j] = change;
}
}
}
This is solve The Problem But even thought i don't Like That Logic || that Code
if you have another one Can You Tell Me About it ??
You can simply use Array.Sort method.
int[] array = new int[5] { 10, 5, 7, 0, 3 };
Array.Sort(array);
On OP's request, I am providing the optimized code. Here complexity is O(Square(N)). I would suggest you use merge sort or quick sort, these have complexity O(NLogN)
int[] array = new int[5] { 10, 5, 7, 0, 3 };
int change = 0;
for (int i = 0; i <= array.Length - 2; i++)
{
for (int j = 0; j <= array.Length - 2; j++)
{
if (array[j] > array[j + 1])
{
change = array[j + 1];
array[j + 1] = array[j];
array[j] = change;
}
}
}
Numbers can shift to the left => check.
Only the first number in the array follows, the rest disappears.
Example how it is right now:
Input array: 1 2 3 4 5 6
Input how many times to shift left: 3
Output: 4 5 6 1
How the Output should be: 4 5 6 1 2 3
Can someone help met with this probably simple solution which I can't find.
var str = Console.ReadLine();
int shift = Convert.ToInt32(Console.ReadLine());
var strArray = str.Split(' ');
var x = strArray[0];
for (var i = 0; i < strArray.Length - shift; i++)
{
strArray[i] = strArray[i + shift];
}
strArray[strArray.Length - shift] = x;
for (var i = 0; i <= strArray.Length - shift; i++)
{
Console.Write(strArray[i] + ' ');
}
You can use Linq to perform your shift, here is a simple method you can use
public int[] shiftRight(int[] array, int shift)
{
var result = new List<int>();
var toTake = array.Take(shift);
var toSkip = array.Skip(shift);
result.AddRange(toSkip);
result.AddRange(toTake);
return result.ToArray();
}
Here is quick fix for you. please check following code.
I shift element to left by 1 position you can change code as par your requirement.
Input array: 1 2 3 4 5 6
Input how many times to shift left: 1
Output : 2 3 4 5 6 1
int[] nums = {1, 2, 3, 4, 5, 6};
Console.WriteLine("\nArray1: [{0}]", string.Join(", ", nums));
var temp = nums[0];
for (var i = 0; i < nums.Length - 1; i++)
{
nums[i] = nums[i + 1];
}
nums[nums.Length - 1] = temp;
Console.WriteLine("\nAfter rotating array becomes: [{0}]", string.Join(", ", nums));
If this is only for strings and the wraparound is necessary I would suggest to use str.Substring(0,shift)
and append it to str.Substring(shift) (don't try to reinvent the weel)
(some info about the substring method: String.Substring )
otherwise the reason why it did not work is because you only saved the first value of the array instead of all the values you wanted to shift.
Do not save only the first value in the array
var x = strArray[0];
use
string[] x = new string[shift];
for (int i = 0; i < shift; i++)
{
x[i] = strArray[i];
}
instead so you collect all the values you need to add to the end.
EDIT: forgot the shifting
Shift the old data to the left
for (int i = 0; i < strArray.Length-shift; i++)
{
strArray[i] = strArray[i+shift];
}
And replace
strArray[strArray.Length - shift] = x;
for
for(int i = 0; i < x.Length; i++){
int newlocation = (strArray.Length - shift)+i;
strArray[newlocation] = x[i];
}
also replace the print loop for
Console.WriteLine(string.Join(" ", strArray));
its easier and makes it one line instead of three lines of code.
(also the docs for the Join function string.Join)
I tried to find 2 or more same elements from array x and then that duplicate to add into new array Y
So if i have in x array number like: 2,5,7,2,8 I want to add numbers 2 into y array
int[] x = new int[20];
Random rnd = new Random();
int[] y = new int[20];
int counter = 0;
for (int i = 0; i < x.Length; i++)
{
x[i] = rnd.Next(1, 15);
for (int j=i+1; j< x.Length; j++)
{
if (x[i] == x[j])
{
y[counter] = x[i];
Console.WriteLine("Repeated numbers are " + y[counter]);
counter++;
}
else
{
Console.WriteLine("There is no repeated numbers, numbers that are in x are " + x[i]);
}
break;
}
}
But having problems with that, when it come to the if loop it doesn't want to proceed with executing if loop (even if condition is true)
If someone could give me some suggestion, that would be helpful, thank you
There are various logical errors in your use of for. You should work more on your logic, because while libraries can be learnt by rote, logical errors are more something that is inside you.
int[] x = new int[20];
Random rnd = new Random(5);
// You don't know the length of y!
// So you can't use arrays
List<int> y = new List<int>();
// First initialize
for (int i = 0; i < x.Length; i++)
{
x[i] = rnd.Next(1, 15);
}
// Then print the generated numbers, otherwise you won't know what numbers are there
Console.WriteLine("Numbers that are in x are: ");
for (int i = 0; i < x.Length; i++)
{
Console.WriteLine(x[i]);
}
// A blank line
Console.WriteLine();
// Then scan
for (int i = 0; i < x.Length; i++)
{
for (int j = i + 1; j < x.Length; j++)
{
if (x[i] == x[j])
{
y.Add(x[i]);
Console.WriteLine("Repeated numbers is " + x[i]);
}
}
}
// Success/failure in finding repeated numbers can be decided only at the end of the scan
if (y.Count == 0)
{
Console.WriteLine("There is no repeated numbers");
}
I've put some comments in the code (plus the changes)
And for debugging purpose, I suggest you use a fixed Random sequence. new Random(5) (or any other number) will return the same sequence every time you launch your program.
Note that if there are multiple repetitions of a number, like { 4, 4, 4 } then the y array will be { 4, 4 }
at first:
why do u use the 'break;' ?
second:
in the first for - loop u assign a random number to x[i]
but then in the nested second loop
u already ask x[j] to check for same values (but that doesn't exist yet)
there are so many ways to check if values are equal,
but i like your approach:
so what i would suggest:
make a for - loop and assign all the random numbers to int[] x
then think again how u can evaluate
x[0] = x[1] or x[2] or x[3] ...
Try to use Linq to find the duplicate in the Array
int[] x = new int[] { 2, 5, 7, 2, 8 };
int[] y;
var result = x.GroupBy(item => item)
.Select(grp => new { key = grp.Key, Count = grp.Count() });
y = result.Where(res => res.Count > 1).Select(res => res.key).ToArray();
int[] array = new int[5] {1,2,3,4,4};
List<int> duplitcateList = array.Where(x => array.Where(y => y == x).Count() > 1).Distinct().ToList();
or you can replace last line of above code with below.
List<int> duplitcateList = array.
GroupBy(x => x).Where(g => g.Count() > 1).Select(g => g.Key).ToList();
above code is using Linq.
suppose your first array (in question x) is array.
Linq will first check for all elements in to list which occur more then once, and select them distinctly and store it to duplicateList
if you need an array at the, you can simply convert this list to array by doing this,
int[] yArray = duplitcateList.ToArray();
Make use of linq in your code , as below
//first populate array x
var duplicates= xArray.GroupBy(x => x)
.Where(g => g.Count() > 1)
.Select(y => y.Key)
.ToArray();
linq query above make use of groupby and find duplicate i.e. element occuring more then one time in you array and then you select those element and return result
I think this will will be the most understandable solution without complicated extension methods:
int[] x = new int[20];
// there can be at most 10 duplicates in array of length of 20 :)
// you could use List<int> to easily add elements
int[] y = new int[10];
int counter = 0;
Random rnd = new Random();
// fill the array
for (int i = 0; i < x.Length; i++)
x[i] = rnd.Next(1, 15);
// iterate through distinct elements,
// otherwise, we would add multiple times duplicates
foreach (int i in x.Distinct())
// if the count of an elements is greater than one, then we have duplicate
if(x.Count(n => n == i) > 1)
{
y[counter] = i;
counter++;
}
I have an array of numbers and I want to display the last digit first, then the 2nd, 3rd, and so on.. How do I do that?
for example, I have: 123, 210, 111
It will display 3, 0, 1, first
then 2, 1, 1,
last, 1, 2, 1
I have this as my code:
for(int x = 0; x < 3; x++){
string n = num[x].ToString(); //converting the array to string
for(int y = length-1; y>=0; y++) //length = number of digits
Console.Write(c[y] + "\n");
}
But it displays the digits of the 1st number first, then the 2nd num, and the 3rd. (3, 2, 1, 0, 1,2, 1,1,1)
You just need to reverse the order of the loops and decrease the letter loop counter:
for(int y = length - 1; y>=0; y--) //length = number of digits
{
for(int x = 0; x < 3; x++){
string n = num[x].ToString(); //converting the array to string
Console.Write(n[y] + "\n");
}
}
Firstly you want to be decreasing your loop counter. Also what is the array c? you have assigned the number to 'n' earlier
Not that clean but w.e.
int[] myInts = { 123, 210, 111 };
string[] result = myInts.Select(x => x.ToString()).ToArray();
int k = 0;
for (int i = 3; i > 0; i--)
{
while (k < 3)
{
Console.Write(result[k].Substring(i - 1, 1));
k++;
}
k = 0;
Console.WriteLine();
}
I have an integer array int[] number = { 3,4,2,5,1};
The minimum number of steps to sort it should be 2. But I am getting 4.
static void Main(string[] args)
{
int[] number = { 3,4,2,5,1};
int result = get_order(number);
Console.ReadKey();
}
public static int get_order(int[] input1)
{
input1 = input1.OrderByDescending(o => o).ToArray();
bool flag = true;
int temp;
int numLength = input1.Length;
int passes = 0;
for (int i = 1; (i <= (numLength - 1)) && flag; i++)
{
flag = false;
for (int j = 0; j < (numLength - 1); j++)
{
if (input1[j + 1] > input1[j])
{
temp = input1[j];
input1[j] = input1[j + 1];
input1[j + 1] = temp;
flag = true;
}
}
passes++;
}
return passes+1;
}
What is the problem and what changes i need to do in my code?
Edit
implement #Patashu, algorithm,
public static int get_order(int[] input1)
{
var sorterArray = input1.OrderByDescending(o => o).ToArray();
var unsortedArray = input1;
int temp1;
int swap = 0;
int arrayLength = sorterArray.Length;
for (int i = 0; i < arrayLength; i++)
{
if (sorterArray[i] != unsortedArray[i])
{
temp1 = unsortedArray[i];
unsortedArray[i] = sorterArray[i];
for (int j = i + 1; j < arrayLength; j++)
{
if (unsortedArray[j] == sorterArray[i])
{
unsortedArray[j] = temp1;
swap++;
break;
}
}
}
}
return swap;
}
The problem with your algorithm is that it only attempts swapping adjacent elements.
3,4,2,5,1 is best sorted by swapping 3 with 5, which is an unadjacent swap, and then 2 with 3.
So, I suggest that you will find a better algorithm by doing the following:
1) First, sort the array into descending order using the built in sorting function of C#.
2) Now, you can use this sorted array as a comparison - iterate through the array from left to right. Every time you see an element in the unsorted array that is != to the element in the same space in the sorted array, look deeper into the unsorted array for the value the sorted array has there, and do one swap.
e.g.
3,4,2,5,1
Sort using Sort -> 5,4,3,2,1 is our sorted array
3 is != 5 - look in unsorted array for 5 - found it, swap them.
Unsorted is now 5,4,2,3,1
4 == 4
2 is != 3 - look in unsorted array for 3 - found it, swap them.
Unsorted is now 5,4,3,2,1
2 == 2
1 == 1
We're at the end of the unsorted array and we did two swaps.
EDIT: In your algorithm implementation, it looks almost right except
instead of
unsortedArray[j] = sorterArray[i];
unsortedArray[i] = temp1;
you had it backwards, you want
unsortedArray[j] = temp1;
unsortedArray[i] = sorterArray[i];
Since you're asking why you're getting 4 steps, and not how to calculate the passes, the correct way to do this is to simply step through your code. In your case the code is simple enough to step through on a piece of paper, in the debugger, or with added debug statements.
Original: 3, 4, 2, 5, 1
Pass: 1: 4, 3, 5, 2, 1
Pass: 2: 4, 5, 3, 2, 1
Pass: 3: 5, 4, 3, 2, 1
Pass: 4: 5, 4, 3, 2, 1
Basically what you see is that each iteration you sort one number into the correct position. At the end of pass one 2 is in the correct position. Then 3, 4, 5.
Ah! But this is only 3 passes you say. But you're actually incrementing passes regardless of flag, which shows you that you actually did one extra step where the array is sorted (in reverse order) but you didn't know this so you had to go through and double check (this was pass 4).
To improve performance, you do not need to start checking the array from the beginning.
Better than the last equal element.
static int MinimumSwaps(int[] arr)
{
int result = 0;
int temp;
int counter = 0;
for (int i = 0; i < arr.Length; ++i)
{
if (arr[i] - 1 == i)
{
//once all sorted then
if(counter==arr.Length)break;
counter++;
continue;
}
temp = arr[arr[i]-1];
arr[arr[i] - 1] = arr[i];
arr[i] = temp;
result++;//swapped
i = counter ;//needs to start from the last equal element
}
return result;
}
At the start:
{ 3,4,2,5,1}; // passes = 0
Round 1 reuslt:
{ 4,3,2,5,1};
{ 4,3,5,2,1}; // passes = 1
Round 2 reuslt:
{ 4,5,3,2,1}; // passes = 2
Round 3 reuslt:
{ 5,4,3,2,1}; // passes = 3 and flag is set to true
Round 4 reuslt:
{ 5,4,3,2,1}; // same result and passes is incremented to be 4
You fail to mention that the array is supposed to be sorted in descending order, which is usually not the default expected behavior (at least in "C" / C++). To turn:
3, 4, 2, 5, 1
into:
1, 2, 3, 4, 5
one indeed needs 4 (non-adjacent) swaps. However, to turn it into:
5, 4, 3, 2, 1
only two swaps suffice. The following algorithm finds the number of swaps in O(m) of swap operations where m is number of swaps, which is always strictly less than the number of items in the array, n (alternately the complexity is O(m + n) of loop iterations):
int n = 5;
size_t P[] = {3, 4, 2, 5, 1};
for(int i = 0; i < n; ++ i)
-- P[i];
// need zero-based indices (yours are 1-based)
for(int i = 0; i < n; ++ i)
P[i] = 4 - P[i];
// reverse order?
size_t count = 0;
for(int i = 0; i < n; ++ i) {
for(; P[i] != i; ++ count) // could be permuted multiple times
std::swap(P[P[i]], P[i]); // look where the number at hand should be
}
// count number of permutations
This indeed finds two swaps. Note that the permutation is destroyed in the process.
The test case for this algorithm can be found here (tested with Visual Studio 2008).
Here is the solution for your question :)
static int MinimumSwaps(int[] arr)
{
int result = 0;
int temp;
int counter = 0;
for (int i = 0; i < arr.Length; ++i)
{
if (arr[i] - 1 == i)
{
//once all sorted then
if(counter==arr.Length)break;
counter++;
continue;
}
temp = arr[arr[i]-1];
arr[arr[i] - 1] = arr[i];
arr[i] = temp;
result++;//swapped
i = 0;//needs to start from the beginning after every swap
counter = 0;//clearing the sorted array counter
}
return result;
}