I try to take only positive numbers from the array and display them in the second array. I copy one array to another but at the output I get only 0.
I’m a beginner in C#, so this is probably an easy thing to do
int[] array = { 12, 23, -22, -765, 43, 545, -4, -55, 43, 12, 351, -999, -87 };
int[] positive = new int[array.Length];
int positiveCounter = 0;
int[] source = new int[7];
Array.Copy(positive, source, 7);
for (int i = 0; i < array.Length; i++)
{
if (array[i] > 0)
{
positive[positiveCounter] = array[i];
positiveCounter++;
}
}
Console.WriteLine("Positive numbers are: ");
foreach (var item in positive)
{
Console.WriteLine(item);
}
You can query initial array with a help of Linq:
using System.Linq;
...
int[] array = ...
int[] positive = array.Where(item => item > 0).ToArray();
To show positive array in one go you can try string.Join:
Console.WriteLine(string.Join(", ", positive));
You can solve the problem with a help of loops (no Linq solution):
int[] array = ...
int positiveCounter = 0;
foreach (int item in array)
if (item > 0)
positiveCounter += 1;
int[] positive = new int[positiveCounter];
int index = 0;
for (int i = 0; i < array.Length; ++i)
if (array[i] > 0)
positive[index++] = array[i];
please note, that Array.Copy copies consequent items which is not guaranteed.
As your request it will take all the positive number from 1st array and store in second array
static void Main(string[] args)
{
ArrayList array =new ArrayList{ 12, 23, -22, -765, 43, 545, -4, -55, 43, 12, 351, -999, -87 };
ArrayList array2 = new ArrayList { };
foreach(int item in array)
{
Console.WriteLine(item);
if (item > 0)
{
array2.Add(item);
}
}
Console.WriteLine("-----------------------------");
foreach (int item in array2)
{
Console.WriteLine(item);
}
}
Related
I have a 2d array: {{1, 2, 2}, {3, 1, 4}}.
I'm trying to make a function to traverse said array, check if each individual element is equal to any other element in the array and then add the number to a list, but I'm stuck.
This is what I've tried so far:
static List<int> FindDuplicates(int[,] array, int totalRows, int totalCols)
{
List<int> duplicates = new List<int>();
int row = 0, col = 0;
//Loops until all elements have been checked
while (true)
{
for (int i = 0; i < totalRows; i++)
{
for (int j = 0; j < totalCols; j++)
{
if (array[row, col] == array[i, j])
{
//Makes sure matching element is only recorded once
if (!duplicates.Contains(array[row, col]))
duplicates.Add(array[row, col]);
}
}
}
//Moves to next element in the array
col++;
if (col > totalCols)
{
col = 0;
row++;
if (row > totalRows)
break;
}
}
return duplicates;
}
Edit: My expected result is {1, 2}, but I keep getting a list with all the elements.
The issue with my function is that it checks the starting element with itself and adds it to the list. Any suggestions on how to avoid that?
If you want to find duplicates, i.e. having
{
{ 1, 2, 2 },
{ 3, 1, 4 }
}
the desired result is List<int>
{ 1, 2 }
you can use Linq:
using System.Linq;
...
static List<int> FindDuplicates(int[,] array) {
return array
.OfType<int>()
.GroupBy(item => item)
.Where(group => group.Count() > 1)
.Select(group => group.Key)
.ToList();
}
No Linq solution can be a loop with HashSet:
static List<int> FindDuplicates(int[,] array) {
List<int> result = new List<int>();
HashSet<int> known = new HashSet<int>();
HashSet<int> duplicates = new HashSet<int>();
foreach (int item in array)
if (!known.Add(item))
if (duplicates.Add(item))
result.Add(item);
return result;
}
Note, that we don't need int totalRows, int totalCols: we can either enumerate items or use array.GetLength(0) and array.GetLength(1)
I'd like help* in creating a method or (linq) expression that can row-wise concatenate lists (of varying lengths) of jagged arrays as the one below:
List<double[][]> orgArrayList = new List<double[][]>();
double[][] one = {
new [] {5d, 6},
new [] {7d, 9}};
double [][] two = {
new [] {5d, 6},
new [] {7d, 9}};
double [][] three= {
new [] {5d, 6},
new [] {7d, 9}};
orgArrayList.AddRange(new[] {one, two, three});
So that the resulting array will be equal to this one:
double[][] expected = {
new [] {5d, 6, 5, 6, 5, 6},
new [] {7d, 9, 7, 9, 7, 9}};
The number of jagged arrays in my input list(s) will be >=1. All arrays within a single list will be jagged with 2 dimensions, but none of the 2 dimensions will have a fixed/known length (size).
*'help' being a euphemism for someone telling me how to do it
You could start with something like this, which appends the elements of each row of add[] to the rows of src[], producing a new 2-dimensional array:
public static double[][] AppendToRows(double[][] src, double[][] add)
{
// Allocate new array to hold elements from src[] and add[]
double[][] res = new double[src.Length][];
// Append elements to each row of res[]
for (int i = 0; i < src.Length; i++)
{
// Allocate row res[i] large enough to hold elements from src[i] and add[i]
res[i] = new double[src[i].Length + add[i].Length];
// Copy/append elements from src[i] to res[i]
int ri = 0;
for (int j = 0; j < src[i].Length; j++)
res[i][ri++] = src[i][j];
// Copy/append elements from add[i] to res[i]
if (i >= add.Length)
continue;
for (int j = 0; j < add[i].Length; j++)
res[i][ri++] = add[i][j];
}
return res;
}
To append multiple arrays together, just call this method multiple times, once for each additional array that needs to be concatenated onto the resulting array.
A more comprehensive solution would be to take a List<double[][]> of input arrays, and to loop through each array in the list as you build each row of the result. But I have left that as an exercise for the reader.
You can create an extension, that will concatenate arrays the way you need, so it will looks like Linq:
public static class Extension
{
public static T[][] ConcatArrays<T>(this T[][] array, T[][] concatWith)
{
var max = Math.Max(array.Length, concatWith.Length);
var result = new T[max][];
for (var index = 0; index < max; index++)
{
var list = new List<T>();
if (index < array.Length)
{
list.AddRange(array[index]);
}
if (index < concatWith.Length)
{
list.AddRange(concatWith[index]);
}
result[index] = list.ToArray();
}
return result;
}
}
So the usage of this is:
var expected = one.ConcatArrays(two).ConcatArrays(three);
Hope it makes sense
As a final solution for my use case I simply combined David's and Valdimir's answer into a single method that can handle lists of varying lengths (>=1).
// ========================================
// My interpretation of David's suggestion
// using Valdimir's solution as a basis
// ========================================
public static double[][] RowWiseConcatListedJaggedArrays(List<double[][]> listOfJaggedArray)
{
var resArray = listOfJaggedArray[0];
for (int rInd = 1; rInd < listOfJaggedArray.Count; rInd++)
{
resArray = resArray.ConcatArrays(listOfJaggedArray[rInd]);
}
return resArray;
}
And putting everything together...
using System;
using System.Collections.Generic;
namespace RowWiseConcat
{
public static class Extension
{
// ====================
// Vladimir's solution
// ====================
public static T[][] ConcatArrays<T>(this T[][] array, T[][] concatWith)
{
var max = Math.Max(array.Length, concatWith.Length);
var result = new T[max][];
for (var index = 0; index < max; index++)
{
var list = new List<T>();
if (index < array.Length)
{
list.AddRange(array[index]);
}
if (index < concatWith.Length)
{
list.AddRange(concatWith[index]);
}
result[index] = list.ToArray();
}
return result;
}
}
class Program
{
// ========================================
// My interpretation of David's suggestion
// using Valdimir's solution as a basis
// ========================================
public static double[][] RowWiseConcatListedJaggedArrays(List<double[][]> listOfJaggedArray)
{
var resArray = listOfJaggedArray[0];
for (int rInd = 1; rInd < listOfJaggedArray.Count; rInd++)
{
resArray = resArray.ConcatArrays(listOfJaggedArray[rInd]);
}
return resArray;
}
static void Main(string[] args)
{
// ... do something that results in orgArrayList, e.g.
double[][] one =
{
new[] {5d, 6},
new[] {7d, 9}
};
double[][] two =
{
new[] {5d, 6},
new[] {7d, 9}
};
double[][] three =
{
new[] {5d, 6},
new[] {7d, 9}
};
List<double[][]> orgArrayList = new List<double[][]>()
{ one, two, three};
// Concat list items
var resArray = RowWiseConcatListedJaggedArrays(orgArrayList);
// ... continue with resArray
}
}
}
I am trying to practice some c# questions and I came across a question where given an integer of array, return the array with elements that can be repeated only N times. So, if I have {1,2,3,4,1,1,2,3} and my N=2, my result should be {1,2,3,4,1,2,3}. I tried something but I get the result as {2,3,4,1,1,2,3}.I don't want the first repeated element be removed.
This is what I have tried :
int[] intArray = {3,2,3,1,3};
int N = 2;
var list = new List<int>(intArray);
var newList = new List<int>();
for (int i = 0; i < list.Count; i++)
{
int occur = 1;
for (int j = i+1; j < list.Count; j++)
{
if (occur < N && list[i] == list[j])
{
occur++;
newList.Add(list[j]);
}
else
{
if (list[i] == list[j] )
list.Remove(list[j]);
}
}
}
foreach (var l in list)
{
Console.WriteLine(l);
}
}
}
I would really appreciate any help or guidance.
I suggest using Dictionary<T, int> to count appearances:
private static IEnumerable<T> RepeatOnly<T>(IEnumerable<T> source, int times) {
Dictionary<T, int> counts = new Dictionary<T, int>();
foreach (var item in source) {
int count;
if (counts.TryGetValue(item, out count))
counts[item] = ++count;
else
counts.Add(item, count = 1);
if (count <= times)
yield return item;
}
}
....
int[] source = new int[] { 1, 2, 3, 4, 1, 1, 2, 3 };
int[] result = RepeatOnly(source, 2).ToArray();
Console.Write(string.Join(Environment.NewLine, result));
I'd use a dictionary to keep track of how many times each integer has been encountered:
int[] intArray = { 1, 2, 3, 4, 1, 1, 2, 3 };
int N = 2;
var lookup = new Dictionary<int, int>();
LIst<int> list = new List<int>();
foreach (int num in intArray)
{
if (!lookup.ContainsKey(num))
{
lookup[num] = 1;
list.Add(num);
}
else if (lookup[num]++ < N)
{
list.Add(num);
}
}
I created a list of arrays. But i am trying to access a specific index to pull the specific array so i can loop through. and get values from it. I am not even sure how to start the code.my list of arrays has items each with 1 aray with 5 valuse. Any suggestions?
How about something like this
List<int[]> l = new List<int[]>();
l.Add(new int[] { 1, 2, 3 });
l.Add(new int[] { 2, 3, 4 });
l.Add(new int[] { 3, 4, 5 });
int a = l[2][2]; // a = 5
You can use the index in the List to loop through a specific array, if you know it's index.
For example, say you have a List named listOfArrays, and you want to loop through the second array:
foreach (int element in listOfArrays[1])
{
// do something with the array
}
listOfArrays[1] will return the int[] in the second position in the List.
Alternatively, you could loop through the entire list and process each array like this:
foreach (int[] arr in listOfArrays)
{
foreach (int element in arr)
{
// do something with the array
}
}
But it sounds like you're looking to simply access a specified array in the list, not all of them.
Hope, some examples help you
List<int[]> myList = new List<int[]>(); // <- MyList is list of arrays of int
// Let's add some values into MyList; pay attention, that arrays are not necessaily same sized arrays:
myList.Add(new int[] {1, 2, 3});
myList.Add(new int[] {4, 5, 6, 7, 8});
myList.Add(new int[] {}); // <- We can add an empty array if we want
myList.Add(new int[] {100, 200, 300, 400});
// looping through MyList and arrays
int[] line = myList[1]; // <- {4, 5, 6, 7, 8}
int result = line[2]; // <- 6
// let's sum the line array's items: 4 + 5 + 6 + 7 + 8
int sum = 0;
for (int i = 0; i < line.Length; ++i)
sum += line[i];
// another possibility is foreach loop:
sum = 0;
foreach(int value in line)
sum += value;
// let's sum up all the arrays within MyList
totalSum = 0;
for (int i = 0; i < myList.Count; ++i) {
int[] myArray = myList[i];
for (int j = 0; j < myArray.Length; ++j)
totalSum += myArray[j];
}
// the same with foreach loop
totalSum = 0;
foreach(int[] arr in myList)
foreach(int value in arr)
totalSum += value;
I have this Array i wrote a function MostFreq that takes an array of integers and return 2 values : the more frequent number in the array and its frequency check this code i worte what do you think ? is there a better way to do it?
static void Main()
{
int [] M={4,5,6,4,4,3,5,3};
int x;
int f=MyMath.MostFreq(M,out x );
console.WriteLine("the most Frequent Item = {0} with frequency = {1}",x,f);
}
=====
in the class Mymath
public static int MostFreq(int[] _M, out int x)
{
//First I need to sort the array in ascending order
int Max_Freq, No_Freq, i, k;
Array.Sort(_M);
k = _M[0];
Max_Freq = 0; i = 0; x = 0;
while (i < _M.Length)
{
//No_Freq= the frequency of the current number
No_Freq = 0;
//X here is the number which is appear in the array Frequently
while (k == _M[i])
{
No_Freq++;
i++;
if (i == _M.Length)
break;
}
if (No_Freq > Max_Freq)
{
//so it will be printed the same
Max_Freq = No_Freq;
x = k;
}
if (i < _M.Length) k = _M[i];
}
return (Max_Freq);
}
LINQ it up. I know this is in VB but you should be able to convert it to C#:
Dim i = From Numbers In ints _
Group Numbers By Numbers Into Group _
Aggregate feq In Group Into Count() _
Select New With {.Number = Numbers, .Count = Count}
EDIT: Now in C# too:
var i = from numbers in M
group numbers by numbers into grouped
select new { Number = grouped.Key, Freq = grouped.Count()};
Assuming you can't use LINQ, I'd probably approach the algorithm like this:
Create Key/Value dictionary
Iterate your array, add a key the dictionary for each unique elem, increment the value each time that element is repeated.
Walk the dictionary keys, and return the elem with the highest value.
This isn't a great solution but it is simple, ContainsKey is an O(1) lookup, so you'll be at most iterating your array twice.
From a software engineering standpoint, I would expect a function called MostFreq to return the element with the highest frequency - not the frequency itself. I would switch your out and return values.
You could eliminate the sort you do at the start by iterating the entire array once, keeping a count of how many times you come across each value in a temporary array, and then iterating the temporary array for the highest number. You could keep both the highest frequency count and the most frequent item throughout, too.
Different sorts have different efficiencies on different types of data, of course, but this would be a worst case of just two iterations.
Edit: Apologies for the repeat... 'Tweren't there when I started :)
Done in 1 pass....
public class PopularNumber
{
private Int32[] numbers = {5, 4, 3, 32, 6, 6, 3, 3, 2, 2, 31, 1, 32, 4, 3, 4, 5, 6};
public PopularNumber()
{
Dictionary<Int32,Int32> bucket = new Dictionary<Int32,Int32>();
Int32 maxInt = Int32.MinValue;
Int32 maxCount = 0;
Int32 count;
foreach (var i in numbers)
{
if (bucket.TryGetValue(i, out count))
{
count++;
bucket[i] = count;
}
else
{
count = 1;
bucket.Add(i,count);
}
if (count >= maxCount)
{
maxInt = i;
maxCount = count;
}
}
Console.WriteLine("{0},{1}",maxCount, maxInt);
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MostFrequentElement
{
class Program
{
static void Main(string[] args)
{
int[] array = new int[] { 4, 1, 1, 4, 2, 3, 4, 4, 1, 2, 4, 9, 3, 1, 1, 7, 7, 7, 7, 7 };
Array.Sort(array, (a, b) => a.CompareTo(b));
int counter = 1;
int temp=0 ;
List<int> LOCE = new List<int>();
foreach (int i in array)
{
counter = 1;
foreach (int j in array)
{
if (array[j] == array[i])
{
counter++;
}
else {
counter=1;
}
if (counter == temp)
{
LOCE.Add(array[i]);
}
if (counter > temp)
{
LOCE.Clear();
LOCE.Add(array[i]);
temp = counter;
}
}
}
foreach (var element in LOCE)
{
Console.Write(element + ",");
}
Console.WriteLine();
Console.WriteLine("(" + temp + " times)");
Console.Read();
}
}
}
Here's an example how you could do it without LINQ and no dictionaries and lists, just two simple nested loops:
public class MostFrequentNumber
{
public static void Main()
{
int[] numbers = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
int counter = 0;
int longestOccurance = 0;
int mostFrequentNumber = 0;
for (int i = 0; i < numbers.Length; i++)
{
counter = 0;
for (int j = 0; j < numbers.Length; j++)
{
if (numbers[j] == numbers[i])
{
counter++;
}
}
if (counter > longestOccurance)
{
longestOccurance = counter;
mostFrequentNumber = numbers[i];
}
}
Console.WriteLine(mostFrequentNumber);
//Console.WriteLine($"occured {longestOccurance} times");
}
}
You get the value of the most frequently occurring number, and (commented) you could get also the numbers of the occurrences.
I know I have an "using Linq;", that's just to convert the initial input string to an int array and to spare a couple of lines and a parsing loop. Algorithm is fine even without it, if you fill the array the "long" way...
Lets suppose the array is as follows :
int arr[] = {10, 20, 10, 20, 30, 20, 20,40,40,50,15,15,15};
int max = 0;
int result = 0;
Map<Integer,Integer> map = new HashMap<>();
for (int i = 0; i < arr.length; i++) {
if (map.containsKey(arr[i]))
map.put(arr[i], map.get(arr[i]) + 1);
else
map.put(arr[i], 1);
int key = map.keySet().iterator().next();
if (map.get(key) > max) {
max = map.get(key) ;
result = key;
}
}
System.out.println(result);
Explanation:
In the above code I have taken HashMap to store the elements in keys and the repetition of the elements as values. We have initialized variable max = 0 ( max is the maximum count of repeated element) While iterating over elements We are also getting the max count of keys.
The result variable returns the keys with the mostly repeated.
int[] arr = { 4, 5, 6, 4, 4, 3, 5, 3 };
var gr = arr.GroupBy(x => x).OrderBy(x => x.Count()).Last();
Console.WriteLine($"The most Frequent Item = {gr.Key} with frequency = {gr.Count()}"); // The most Frequent Item = 4 with frequency = 3
int[] numbers = new int[] {1, 2, 3, 2, 1, 4, 2};
Dictionary<int, int> numberCounts = new Dictionary<int, int>();
foreach (int number in numbers)
{
if (numberCounts.ContainsKey(number))
{
numberCounts[number]++;
}
else
{
numberCounts[number] = 1;
}
}
int maxCount = numberCounts.Values.Max();
int mostFrequentNumber = numberCounts.Where(x => x.Value == maxCount).OrderByDescending(x => x.Key).First().Key;
Console.WriteLine("Most frequent number: " + mostFrequentNumber);
int count = 1;
int currentIndex = 0;
for (int i = 1; i < A.Length; i++)
{
if (A[i] == A[currentIndex])
count++;
else
count--;
if (count == 0)
{
currentIndex = i;
count = 1;
}
}
int mostFreq = A[currentIndex];