A multidimensional array with systematic selected elements in C# - c#

The wished output is a lot of array that looks like this:
public decimal [] array 1 = {1, 1, 0, 0, 0};
public decimal [] array 2 = {0, 1, 1, 0, 0};
public decimal [] array 3 = {0, 0, 1, 1, 0};
public decimal [] array 4 = {0, 0, 0, 1, 1};
The dimension does not fit my problem, because the problem demands a array of 14 elements, but the idear is the same. The question is how do I create this in a smart way. I tried a "for loop" creating array 1, but as the loop carried on it overwrote array 1 with array 2:
class Program
{
public decimal[] array_1 = { 0, 0, 0, 0, 0 };
public void Main(string[] args)
{
for (int i = 0; i < 5; i++)
{
if (i == 0)
{
array_1 [i] = 1;
array_1 [i + 1] = 1;
}
else if (i == 1)
{
array_1[i] = 1;
array_1[i + 1] = 1;
}
else if (i == 2)
{
array_1[i] = 1;
array_1[i + 1] = 1;
}
else if (i == 3)
{
array_1[i] = 1;
array_1[i + 1] = 1;
}
else if (i == 4)
{
array_1[i] = 1;
array_1[i + 1] = 1;
}
}
}
}
The output of the above is a array with only ones and not four different arrays as firstly wished.

decimal[][] arrays = { array_1, array_2, array_3, array_4 };
for (int a = 0; a < arrays.Length; a++) {
for (int i = 0; i < arrays[a].Length; i++) {
arrays[a][i] = i == a || i == a+1 ? 1 : 0;
}
}
Or, you can create one two-dimensional array:
decimal[,] array = new decimal[4, 5];
for (int row = 0; row < array.GetLength(0); row++) {
for (int column = 0; column < array.GetLength(1); column++) {
array[row, column] = column == row || column == row+1 ? 1 : 0;
}
}

Use multidimensional array:
class Program
{
public decimal[,] arrayObj = new decimal[5, 5];
public void Main(string[] args)
{
for (int i = 0; i < 4; i++)
{
arrayObj[i][i] = 1;
arrayObj[i+1] = 1;
}
}

If you want a collection (say, decimal[][] - jagged array) of arrays, I suggest using Linq:
int n = 4;
decimal[][] arrays = Enumerable.Range(1, n)
.Select(index => Enumerable
.Range(1, n + 1)
.Select(x => (decimal) (x == index || x == index + 1 ? 1 : 0))
.ToArray())
.ToArray();
and then use the collection
decimal array1 = arrays[0];
Test
string report = string.Join(Environment.NewLine, arrays
.Select(array => string.Join(" ", array)));
Outcome:
1 1 0 0 0
0 1 1 0 0
0 0 1 1 0
0 0 0 1 1
If you insist on 2d array:
int n = 4;
decimal[,] arrays = new decimal[n, n + 1];
for (int i = 0; i < arrays.GetLength(0); ++i) {
arrays[i, i] = 1;
arrays[i, i + 1] = 1;
}

Related

Digit difference sort

So I am trying to solve this task "Digit Difference Sort" on Codefights
Given an array of integers, sort its elements by the difference of their largest and smallest digits.
In the case of a tie, that with the larger index in the array should come first.
Example
For a = [152, 23, 7, 887, 243], the output should be digitDifferenceSort(a) = [7, 887, 23, 243, 152].
Here are the differences of all the numbers:
152: difference = 5 - 1 = 4;
23: difference = 3 - 2 = 1;
7: difference = 7 - 7 = 0;
887: difference = 8 - 7 = 1;
243: difference = 4 - 2 = 2.
23 and 887 have the same difference, but 887 goes after 23 in a, so in the sorted array it comes first.
I have an issue with two numbers having the same difference. Here's what I wrote so far:
int[] digitDifferenceSort(int[] a) {
return a.OrderBy(x => difference(x)).ToArray();
}
int difference(int x)
{
int min = 9, max = 0;
do
{
int tmp = x % 10;
min = Math.Min(min, tmp);
max = Math.Max(max, tmp);
} while ((x /= 10) > 0);
return max - min;
}
Didn't do much (for example the output is still [7, 23, 887, 243, 152] rather than [7, 887, 23, 243, 152])
How do I make element with larger index come first in result? What should I use instead of OrderBy?
I don't consider your difference method, i assume it works fine.
To your question: you have to keep revered order of the array (that the items with the same difference arrive will be sorted reverse). To do it, you could just reverse you input array: all items with not identical difference will be ordered correctly, and with the same differece will be ordered reversed:
int[] digitDifferenceSort(int[] a)
{
return a.Reverse().OrderBy(x => difference(x)).ToArray();
}
Following is my code for the above question digit difference sort. I am also getting output when running in Eclipse but when I paste the code on code signal it gives me a null pointer exception.
package NormalPrograms;
import java.util.ArrayList;
import java.util.Collections;
public class DigitDifferenceSort {
// For index wise sorting in descending order
public static int[] sortingnumberindexwise(int[] a, ArrayList<Integer> index) {
int k = 0;
int[] res = new int[index.size()];
int[] finalres = new int[index.size()];
for (int i = a.length - 1; i >= 0; i--) {
for (int j = 0; j < index.size(); j++) {
if (a[i] == (int) index.get(j)) {
res[k] = i;
index.remove(j);
k++;
break;
}
}
}
int g = 0;
k = 0;
for (int i = 0; i < res.length; i++) {
finalres[g] = a[res[k]];
g++;
k++;
}
return finalres;
}
public static int[] finddigitDifferenceandSort(int[] p) {
int[] finres = new int[p.length];
for (int i = 0; i < finres.length; i++) {
finres[i] = p[i];
}
// This finres array act as an temp array and reused to make final result array
int digit = 0;
ArrayList<Integer> A = new ArrayList<Integer>();
ArrayList<ArrayList<Integer>> B = new ArrayList<ArrayList<Integer>>();
for (int i = 0; i < 10; i++) {
B.add(new ArrayList<Integer>());
}
for (int i = 0; i < p.length; i++) {
int temp = 0;
temp = p[i];
while (p[i] > 0) {
digit = p[i] % 10;
p[i] /= 10;
A.add(digit);
}
int b = Collections.max(A);
int c = Collections.min(A);
int diff = b - c;
B.get(diff).add(temp);
A.clear();
}
for (int i = 0; i < B.size(); i++) {
if (B.get(i).size() > 1) {
ArrayList<Integer> C = new ArrayList<Integer>();
for (int k = 0; k < B.get(i).size(); k++) {
C.add(B.get(i).get(k));
}
B.get(i).clear();
for (int j : sortingnumberindexwise(finres, C)) {
B.get(i).add(j);
}
} else {
continue;
}
}
int k = 0;
for (int i = 0; i < B.size(); i++) {
for (int j = 0; j < B.get(i).size(); j++) {
if (B.get(i).size() == 0)
continue;
else {
finres[k] = B.get(i).get(j);
k++;
}
}
}
return finres;
}
public static void main(String[] args) {
int[] a = { 12, 21, 1, 1, 1, 2, 2, 3 };
for (int i : finddigitDifferenceandSort(a)) {
System.out.print(i + " ");
}
}
}

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

Make list of number from paired number in C#

I have a list of sublists with paired indexed number and its binary value. For example:
Variable Value
route.x[0,0] 0
route.x[0,1] 1
route.x[0,2] 0
route.x[0,3] 0
route.x[1,0] 0
route.x[1,1] 0
route.x[1,2] 0
route.x[1,3] 1
route.x[2,0] 0
route.x[2,1] 0
route.x[2,2] 0
route.x[2,3] 0
route.x[3,0] 0
route.x[3,1] 0
route.x[3,2] 1
route.x[3,3] 0
If the value of route.x[i,j] is 1, then make a new list which contains that number in sequence. For that example, the new list will be: route = 0 1 3 2
So far, i have made this code:
//find optimal route
var route = new List<List<int>>();
for (int j = 0; j < C+1; ++j)
{
if (routeopt.x[0, j] != 1)
continue;
List<int> subroute = new List<int>();
subroute.Add(0);
subroute.Add(j);
route.Add(subroute);
}
This code's result is route = 0 1. After that I use this code to add new number (3 and 2).
for (int i = 1; i < C+1; ++i)
{
for (int j = 1; j < C+1; j++)
{
if (routeopt.x[i, j] == 1)
{
List<int> targetlist = route.Single(r => r.Contains(i));
targetlist.Add(j);
}
}
}
This code is worked if only I have a route.x[i,j] with value 1 in ordered number. But if it is not ordered, for example (I only show variable with value 1):
Variable Value
route.x[0,4] 1
route.x[0,3] 1
route.x[4,1] 1
route.x[1,2] 1
It should be route = 0 3 and route = 0 4 1 2. But it showed Sequence contains no matching element because index 1 is not contained in route = 0 3 or route = 0 4. How to handled that problem? Thank you
Try below code. It returns list of all routes. The List of int has route in inverse order so while displaying/using you should take care of it.
const int C = 4;
static int[,] route_x = new int[5, 5];
static void Main(string[] args)
{
var allRoutes = FindRoutes();
System.Console.ReadLine();
}
private static List<List<int>> FindRoutes()
{
route_x[0, 0] = 0;
route_x[0, 1] = 1;
route_x[0, 2] = 0;
route_x[0, 3] = 0;
route_x[1, 0] = 0;
route_x[1, 1] = 0;
route_x[1, 2] = 0;
route_x[1, 3] = 1;
route_x[2, 0] = 0;
route_x[2, 1] = 0;
route_x[2, 2] = 0;
route_x[2, 3] = 0;
route_x[3, 0] = 0;
route_x[3, 1] = 0;
route_x[3, 2] = 1;
route_x[3, 3] = 0;
route_x[0, 4] = 1;
route_x[0, 3] = 1;
route_x[4, 1] = 1;
route_x[1, 2] = 1;
var routes = new List<List<int>>();
for (int i = 0; i < C + 1; i++)
{
if (route_x[0, i] == 1)
{
var subroutes = FindNextRoute(i);
foreach (var item in subroutes)
{
item.Add(0);
routes.Add(item);
}
}
}
return routes;
}
private static List<List<int>> FindNextRoute(int i)
{
var subroute = new List<List<int>>();
bool found = false;
for (int j = 0; j < C + 1; j++)
{
if (route_x[i, j] == 1)
{
found = true;
var tempRoutes = FindNextRoute(j);
foreach(var item in tempRoutes)
{
item.Add(i);
subroute.Add(item);
}
}
}
if (!found)
{
var singleitem = new List<int>();
singleitem.Add(i);
subroute.Add(singleitem);
}
return subroute;
}
I already found it by myself. After I got the first part, I use this code to add new number. Here is my code:
foreach (var subroute in route)
{
int r = 0;
while (r != subroute[subroute.Count - 1])
{
r = subroute[subroute.Count-1];
for (int j = 1; j < C + 1; j++)
{
if (routeopt.x[r, j] == 1)
subroute.Add(j);
}
}
}
The Single method expects there is exactly 1 return value. if not it will throw an exception.
Try SingleOrDefault. This will return null if there is no element found.
List<int> targetlist = route.SingleOrDefault(r => r.Contains(i));
if(targetList != null)
targetlist.Add(j);
Edit:
This will still crash if there are 2 lists that contain i.
To avoid this you could use FirstOrDefault

Replacing two consecutive cell in an array with one cell

I was just asking if there is a simple way of doing this.
i.e. Replacing two consecutive cell with one cell having different value.
For ex: - if my array =[0,3,1,2,3,4], and i want to replace index 0,and 1 with the value 5
to become like this array=[5,1,2,3,4]
Can you guys suggest some simple way for doing this.
i do this code but there is something wrong:
int J = 0;
if (max != 1)
{
for (int iii = 0; iii < output.Length -1; iii++)
{
if ((output[iii] == imax) && (output[iii + 1] == jmax))
{
temp = temp + 1;
output[J] = Convert.ToByte(temp);
J = J + 1;
iii = iii + 1;
}
else
{
output[J] = output[iii];
J = J + 1;
output[J] = output[iii + 1];
}
}
}
because when i want to check the 2 consecutive index ,i want to pass them to the anther 2 index
If you care about performance you want to do as little operations that can harm performance. Try this extension method:
public static int[] ReplaceConsecutiveCells(this int[] array, int startIndex, int replaceWith)
{
int[] targetArray = new int[array.Length - 1];
for (int i = 0; i < array.Length; i++)
{
if (i < startIndex)
{
targetArray[i] = array[i];
}
else if (i == startIndex)
{
targetArray[i] = replaceWith;
}
else if (i == startIndex + 1)
{
// no action
}
else
{
targetArray[i - 1] = array[i];
}
}
return targetArray;
}
Use it like this:
array = array.ReplaceConsecutiveCells(0, 5);
int[] array = new int[] { 0, 3, 1, 2, 3, 4 };
List<int> list = array.ToList();
list.RemoveRange(0,2);
list.Insert(0, 5);
array = list.ToArray();
Yet another variant
int[] array = new int[] { 0, 3, 1, 2, 3, 4 };
Array.Reverse(array);
Array.Resize(ref array, 5);
Array.Reverse(array);
array[0] = 5;
do
{
RNG_NXT =RNG +1;
for (int iii = 0; iii <Nold -1; iii++)
{
if ((output[iii] == imax) && (output[iii + 1] == jmax))
{
output[J] = Convert.ToByte(RNG_NXT);
J = J + 1;
iii = iii + 1;
}
else
{
output[J] = output[iii];
J = J + 1;
}
}
RNG++;
}
while( RNG < RNG_MAX) ;

How do you go through two int arrays and sum their values if they exist

I want to create a method that I can send two arrays (that will be containing ints). These arrays wont necessarily be equally long. for example first array could have an index of 15 while the second array has an index of 12. in that case I want to add array1 and array2 for the first 12 then just get the value of array1 for the last 3.
I thought something like this:
int[] ArrTotal(int[] array1, int[] array2)
{
int[] total = new int[15];
for (int i = 0; i < 15; i++)
{
if (array1[i] != null && array2[i] != null)
{
total[i] = array1[i] + array2[i];
}
else if(array1[i] != null)
{
total[i] = array1[i];
}
else if (array2[i] != null)
{
total[i] = array2[i];
}
else
{
total[i] = 0;
}
}
return total;
}
Problem is that I can't check and see if an int array is null. I read something about doing an:
If(i < array1.Length)
but that does not seem to work either, it says it will always be true in my case.
Am I on the right track at all or is there some major flaw I'm missing? :)
How about:
int[] ArrTotal(int[] a, int[] b)
{
if (a == null || b == null)
{
return (int[])(a ?? b).Clone();
}
int length = Math.Max(a.Length, b.Length);
int[] result = new int[length];
for (int i = 0; i < length; i++)
{
int sum = 0;
if (a.Length > i) sum += a[i];
if (b.Length > i) sum += b[i];
result[i] = sum;
}
return result;
}
Try to check lengths of both arrays before:
int length = (array1.Length < array2.Length ? array1.Length : array2.Length);
Then iterate and assign only to array indeces from 0 to length of the shorter array - 1:
for (int i = 0; i < 15; i++)
if (i < length)
newArray[i] = array1[i] + array2[i];
else
newArray[i] = 0;
int[] a1 = new int[] { 1, 2, 3, 2, 3, 1 };
int[] a2 = new int[] { 1, 2, 3, 2, 3, 1, 3, 2, 3 };
List<int> r = new List<int>();
bool a1_longer = (a1.Length > a2.Length);
int length_diff = Math.Abs(a1.Length - a2.Length);
int length = (a1_longer ? a2.Length : a1.Length);
for (int i = 0; i < length; i++) r.Add(a1[i] + a2[i]);
for (int i = 0; i < length_diff; i++) {
r.Add(a1_longer ? a1[length + i] : a2[length+i]);
}
r.ToArray();
You may use Linq for it:
int[] ArrTotal(int[] array1, int[] array2)
{
return Enumerable.Repeat(0, Math.Max(array1.Length,array2.Length))
.Select((a, index) => a +
((array1.Length > index) ? array1[index] : 0)+
((array2.Length > index) ? array2[index] : 0))
.ToArray();
}
Using Linq you can do this (which will handle null arrays). You will need a using System.Linq at the top of the source code file:
int[] ArrTotal(int[] array1, int[] array2)
{
if ((array1 == null) && (array2 == null))
return new int[0]; // Zero length array - put some other number here if you need!
else if (array1 == null)
return (int[])array2.Clone(); // Result will just be a copy of the non-null array.
else if (array2 == null)
return (int[]) array1.Clone(); // Result will just be a copy of the non-null array.
else
{
int skip = Math.Min(array1.Length, array2.Length);
return Enumerable
.Zip(array1, array2, (i1, i2) => i1 + i2)
.Concat(array1.Skip(skip))
.Concat(array2.Skip(skip))
.ToArray();
}
}

Categories

Resources