Modyfing the objects sequence between arrays C# simple solution - c#

I was trying to find (using a code listed below) a simple solution for copying all the objects which are stored in first array, to second array, with changing paralelly the index of objects in second array + 1, so the object[0] in first array would be equal to object[1] in second one, and the last object[9] in the first one would be equal to the object[0] in second.
While trying to start code which I've written I've received message, which stated that "Destination array was not long enough Check destIndex and length, and the array's lower bounds", I'm just starting with arrays part at c#, so I'd be very gratefull for any quidance.
static void Main(string[] args)
{
int[] first = {10, 11, 12, 13, 14, 15, 16, 17, 18, 19};
int[] second = new int[first.Length];
Array.Copy(first, 0, second, 1, 10);
foreach (int x in second)
{
Console.WriteLine("{0}", x);
}
Console.ReadKey();
}
}

Instead of Array.Copy and foreach you can do this:
for (int i = 0; i < first.Length; i++)
second[i == first.Length - 1 ? 0 : i + 1] = first[i];
It just goes from i = 0 to i = first.Length-1, copying the element at that index in first to that index plus 1 in second.

If the idea is to rotate the array one position forward, you can use a simple for:
static void Main(string[] args)
{
int[] first = {10, 11, 12, 13, 14, 15, 16, 17, 18, 19};
int[] second = new int[first.Length];
for (int k = 0; k < first.Length; k++)
second[(k == (first.Length - 1))? 0: k + 1] = first[k];
foreach (int x in second)
{
Console.WriteLine("{0}", x);
}
Console.ReadKey();
}

Related

How to output biggest array elements if they repeats and need to be output all

I have an array. I need to find biggest element of it. If element repeats in array once again, I need to output and it. What is the program to output all biggest elements, if they repeats?
I tried to create new array, but somehow it did not work.
For example
int[] array = { 15, 2, 16, 16, 7, 3, 16};
And expected output
16 16 16
int[] array = { 1, 2, 1, 16, 7, 3, 15 };
expected output
16
A more "old fashioned" approach would be to walk through the array and keep track of the largest item (and the number of times you encounter it) as you go:
var items = new[] {15, 2, 16, 16, 7, 3, 16};
var largest = int.MinValue;
var count = 0;
// Walk through each item in the array, and compare it to the largest one found
// If it equals the largest, then increment our count. If it's greater than
// the largest, then set largest equal to this item and set count equal to 1.
foreach (var item in items)
{
if (item == largest)
{
count++;
}
else if (item > largest)
{
largest = item;
count = 1;
}
}
// Output the largest item 'count' times
for (int i = 0; i < count; i++)
{
Console.Write(largest + " ");
}

Counting huge permutations - counting elements and getting nth element

I am using this library for combinatorics:
https://github.com/eoincampbell/combinatorics/
What I need is to find n-th permutation and count elements of fairly large sets (up to about 30 elements), but I get stopped in my tracks before even starting, check out this code:
int[] testSet = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21};
var permutation = new Permutations<int>(testSet);
var test = permutation.Count;
Everything works peachy just until 20 element large set, once I add 21st, permutations stop working right, eg.
here is what permutation.Count returns:
-4249290049419214848
which is far from being the right number.
I am assuming that it all boils down to how huge numbers I use - overflowing ints/longs that library uses. That is why, I am asking for an advice - is there a library? approach? or a fairly quick to implement way to have combinatorics work on bigintegers?
Thanks!
Get the number of possible permuations.
The number of permutations is defined by nPr or n over r
n!
P(n,r) = --------
(n - r)!
Where:
n = Number of objects
r = the size of the result set
In your example, you want to get all permutations of a given list. In this case n = r.
public static BigInteger CalcCount(BigInteger n, BigInteger r)
{
BigInteger result = n.Factorial() / (n - r).Factorial();
return result;
}
public static class BigIntExtensions
{
public static BigInteger Factorial(this BigInteger integer)
{
if(integer < 1) return new BigInteger(1);
BigInteger result = integer;
for (BigInteger i = 1; i < integer; i++)
{
result = result * i;
}
return result;
}
}
Get the nTh permutation
This one depends on how you create/enumerate the permutations. Usually to generate any permutation you do not need to know all previous permutations. In other words, creating a permutation could be a pure function, allowing you to directly create the nTh permutation, without creating all possible ones.
This, however, depends on the algorithms used. But will potentially be a lot faster to create the permutation only when needed (in contrast to creating all possible permutations up front -> performance and very memory heavy).
Here is a great discussion on how to create permutations without needing to calculate the previous ones: https://stackoverflow.com/a/24257996/1681616.
This is too long for a comment, but wanted to follow up on #Iqon's solution above. Below is an algorithm that retrieves the nth lexicographical permutation:
public static int[] nthPerm(BigInteger myIndex, int n, int r, BigInteger total)
{
int j = 0, n1 = n;
BigInteger temp, index1 = myIndex;
temp = total ;
List<int> indexList = new List<int>();
for (int k = 0; k < n; k++) {
indexList.Add(k);
}
int[] res = new int[r];
for (int k = 0; k < r; k++, n1--) {
temp /= n1;
j = (int) (index1 / temp);
res[k] = indexList[j];
index1 -= (temp * j);
indexList.RemoveAt(j);
}
return res;
}
Here is a test case and the result of calling nthPerm using the code provided by #Iqon.
public static void Main()
{
int[] testSet = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21};
BigInteger numPerms, n, r;
n = testSet.Length;
r = testSet.Length;
numPerms = CalcCount(n, r);
Console.WriteLine(numPerms);
BigInteger testIndex = new BigInteger(1234567890987654321);
int[] myNthIndex = nthPerm(testIndex, (int) n, (int) r, numPerms);
int[] myNthPerm = new int[(int) r];
for (int i = 0; i < (int) r; i++) {
myNthPerm[i] = testSet[myNthIndex[i]];
}
Console.WriteLine(string.Join(",", myNthPerm));
}
// Returns 1,12,4,18,20,19,7,5,16,11,6,8,21,15,13,2,14,9,10,17,3
Here is a link to ideone with working code.
You can useJNumberTools
List<String> list = new ArrayList<>();
//add elements to list;
JNumberTools.permutationsOf(list)
.uniqueNth(1000_000_000) //next 1 billionth permutation
.forEach(System.out::println);
This API will generate the next nth permutation directly in lexicographic order. So you can even generate next billionth permutation of 100 items.
for generating next nth permutation of given size use:
maven dependency for JNumberTools is:
<dependency>
<groupId>io.github.deepeshpatel</groupId>
<artifactId>jnumbertools</artifactId>
<version>1.0.0</version>
</dependency>

How can I find greatest number in array of number

I have an array like this
int[] intnumber = new int[]{10,25,12,36,100,54,68,75,63,24,1,6,9,5};
I want to find the greatest number and make it In order from largest to smallest
like this
100,75,68,63,54,36,25,24,12,10,9,6,5,1
int[] intnumber = new int[] { 10, 25, 12, 36, 100, 54, 68, 75, 63, 24, 1, 6, 9, 5 };
int maxValue = intnumber.Max();
You can sort the array for viewing elements in ascending order
Array.Sort(intnumber);
Array.Reverse(intnumber);
foreach (var str in intnumber )
{
MessageBox.Show(str.ToString());
}
Try this,
int[] intnumber = new int[] { 10, 25, 12, 36, 100, 54, 68, 75, 63, 24, 1, 6, 9, 5 };
//Maximum Value
int maxValue = intnumber.Max();
//Maximum Index
int maxIndex = intnumber.ToList().IndexOf(maxValue);
You can use :
int[] intnumber = new int[]{10,25,12,36,100,54,68,75,63,24,1,6,9,5};
Array.Sort(intnumber );
Array.Reverse(intnumber );
int max = intnumber[0];
exactly output that you want.
int[] intnumber = new int[] { 10,25,12,36,100,54,68,75,63,24,1,6,9,5 };
Array.Sort<int>(intnumber ,
new Comparison<int>(
(i1, i2) => i2.CompareTo(i1)
));
intnumber .Dump();
P.S. To run this demo you need to follow these steps:
1.Download LINQPad.
2.Download the demo file, open it with LINQPad and hit F5.
I found my answer with your helps
Console.WriteLine("How many Numbers Do you want? ");
int counter = int.Parse(Console.ReadLine());
double[] numbers = new double[counter];
for (int i = 0; i < numbers.Length; i++)
{
Console.Write((i + 1) + " : ");
numbers[i] = Convert.ToDouble(Console.ReadLine());
}
Console.WriteLine("_______________________________________________");
Array.Sort(numbers);
Array.Reverse(numbers);
foreach (double item in numbers)
{
Console.WriteLine(item);
}
Console.WriteLine("_______________________________________________");
Console.WriteLine("The Greatest Number is " + numbers[0]);
Console.ReadKey();
Let intNumbers be the array that you are using, Then you can use the .Max() method of the Array Class to get the maximum value, that is the greatest number. If you want to Sort the Current array means You have to use the .Sort() method. The requirement is simply Printing the Array in descending order means you have to use the .OrderBy()
int[] inputNumbers = new int[] { 15, 12, 11, 23, 45, 21, 2, 6, 85, 1 };
Console.WriteLine("Input Array is : {0}\n",String.Join(",",inputNumbers.OrderByDescending(x=>x)));
Console.WriteLine("Max value in the array is : {0}\n",inputNumbers.Max());
Console.WriteLine("Array in descending order : {0}\n",String.Join(",",inputNumbers.OrderByDescending(x=>x)));
Here is a working Example
int max = Integer.MIN_VALUE;
for (int i =0; i < intnumber.length; i++)
{
int num = intnumber[i];
//Check to see if num > max. If yes, then max = num.
}
System.out.println(max);

Array not displaying properly

This is homework assignment for school, but I'm begging for someone to just correct my code. I've been working at this for two days and I think I have everything worked out except I can't get it to work as a 2D Array, so I set this up temporarily just to try to figure things out, but I'm digging myself deeper into a hole I think.
The assignment requires that two dice be rolled 36,000 times and then the results for each sum be displayed on the right, and the sum of the two dice on the left, like this in a 2D array:
12 850
11 1020
10 1200
...
2 900
I've got the right column displaying correctly, but the left column won't display the sums, it just displays "System.Int32[]" a bunch of times.
Here's the code:
Random rand = new Random();
const int ARRAY_SIZE = 13;
const double DICE_ROLLS = 36000;
int sum = 0;
int die1 = 0;
int die2 = 0;
int[] sums = new int[ARRAY_SIZE];
int[] dice = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
for (int i = 0; i < DICE_ROLLS; i++ )
{
die1 = rand.Next(1, 7);
die2 = rand.Next(1, 7);
sum = die1 + die2;
sums[sum] += 1;
}
for (int i = 2; i < sums.Length; i++)
{
Console.WriteLine("{0,2} {1,8}", dice, sums[i]);
}
In the spirit of the homework assignment, rather than fixing the code outright, I will try to explain the parts you need to fix, and let you do the actual fixing.
The primary issue in your code is that you are trying to print dice as the value for the left column of the output, rather than individual elements of dice (e.g. dice[i]).
Note, however, that you can't just use dice[i], because your dice array has fewer elements in it than the sums array. If you just replaced dice with dice[i] in your WriteLine() statement, you'd get an index-out-of-bounds exception.
IMHO, the best way to address this is to initialize sums with 11 elements instead of 13, and then when tracking the sums (i.e. in your first loop), subtract 2 from the actual sum value to get the index for the sums array:
sums[sum - 2] += 1;
Then in your second loop, you can safely just use i to index both arrays.
I hope that helps. Please feel free to ask for any clarifications and good luck with your assignment.
Since you'll be using a 2d array you'll want to do something like this:
var rand = new Random();
const double diceRolls = 36000;
var sums = new[,] {{2, 0}, {3, 0}, {4, 0}, {5, 0}, {6, 0}, {7, 0}, {8, 0}, {9, 0}, {10, 0}, {11, 0}, {12, 0}};
for (var i = 0; i < diceRolls; i++)
{
var die1 = rand.Next(1, 7);
var die2 = rand.Next(1, 7);
var sum = die1 + die2;
sums[sum - 2, 1] += 1;
}
for (var i = 0; i < sums.GetLength(0); i++)
{
Console.WriteLine("{0,2} {1,8}", sums[i, 0], sums[i, 1]);
}
Note 1: sum - 2. Since the array length is only 11 you need to subtract 2 from the dice value. (0-10 instead of 2-12).
Note 2: sums.GetLength(0). If you use sums.Length you'll get 22 since there actually are 22 elements in the array. You need to get the length for rank 0
Note 3: Since you're dealing with 2d arrays you'll have the sum of the dice roll in sum[i, 0] and the total count in sum[i, 1].

Increasing Array with Rows

Say I have an an array of numbers:
int[] that = new [] {1, 2, 3, 2, 4, 8, 9, 7};
I'm trying to display them so that the numbers that are increasing have their own line.
For example the result would be:
1 2 3
2 4 8 9
7
I'm able to do the first row using,
for (int i = 1; i < that.Length; i++)
{
if (that[i-1] < that[i])
{
Console.Write(that[i-1] + " ");
}
}
The thing is this works for the first row because 1-3 are increasing but stops after that.
I'm not exactly sure how to continue so that 2 4 8 9, then 7 are written.
I have a feeling this is homework so I'm going to leave the actual coding to you. But here's how to do it in plain language:
Have a variable where we store the previous value. Let's call it oldValue, and start it with zero (if you're only using positive numbers in your array).
Go through the array one item at a time.
Check to see if that number is larger than oldValue.
If FALSE, print the new line character. "\n" in C#.
Print that number and make oldValue equal that number.
Unless your numbers are finished get the next number and go to step 3.
You never create a new line.
int[] arr = new[] {1, 2, 3, 2, 4, 8, 9, 7};
for(var i = 0; i < arr.Length; i++){
if(i == 0 || ((i < arr.Length - 1) && arr[i] < arr[i + 1])){
Console.Write(arr[i]);
} else {
Console.Write("{0}\n", arr[i]);
}
}
Output:
123
2489
7
Couple of remarks:
Avoid the usage of this as a variable name. It's a reserved
keyword.
Use \n as a newline character.
There are a number of ways you can do this, either by appending a string with characters until a lesser one is reached and then using the Console.WriteLine() command to write the entire string at once, or (the easier way given your code) which is to simply test for the new value being lesser than the previous and inserting a newline character into your text.
// Start at zero
for (int i = 0; i < this.Length; i++)
{
// If this is not the first element in the array
// and the new element is smaller than the previous
if (i > 0 && this[i] < this[i-1])
{
// Then insert a new line into the output
Console.Write(Environment.NewLine);
}
Console.Write(this[i] + " ");
}
int[] numbers = new int[] { 1, 2, 3, 2, 4, 8, 9, 7 };
String orderedNumbers = String.Empty;
for (int i = 0; i < numbers.Length; i++)
{
if (i == 0 || numbers[i] > numbers[i - 1])
{
orderedNumbers += numbers[i].ToString();
}
else
{
orderedNumbers += System.Environment.NewLine + numbers[i].ToString();
}
}
MessageBox.Show(orderedNumbers);

Categories