C# For Loop and Array (practice exercise) - c#

I'm trying to pick up C# and have been doing some practice programs. In this one, I try to transfer the integers in practiceArray to practiceArray2 but am unsuccessful, instead obtaining this as the output:
System.Int32[]
System.Int32[]
The code of my program is as follows:
static void Main(string[] args)
{
int[] practiceArray = new int[10] {2,4,6,8,10,12,14,16,18,20 };
int[] practiceArray2 = new int[practiceArray.Length];
for (int index = 0; index < practiceArray.Length; index++)
{
practiceArray2[index] = practiceArray[index];
}
Console.WriteLine(practiceArray);
Console.WriteLine(practiceArray2);
}

Console.WriteLine doesn't have any complicated logic for outputting complex objects, it just calls ToString() if it's not a string. You need to concatenate the values in the arrays manually, using string.Join etc.
For instance: Console.WriteLine(string.Join(", ", practiceArray));

int[] practiceArray = new int[10] { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 };
int[] practiceArray2 = new int[practiceArray.Length];
for (int index = 0; index < practiceArray.Length; index++)
{
practiceArray2[index] = practiceArray[index];
}
foreach (int pArray in practiceArray)
Console.Write(pArray + " ");
foreach (int pArray2 in practiceArray2)
Console.Write(pArray2 + " ");
Console.Read();

Related

How to return an array fibonaci numbers in C #?

I want to make a function that takes an array of integers as input and print an array of int as Fibonaci series like: third element= second element + first element.
Here is my code so far:
static void Result(int[] arr)
{
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] < 0)
Console.WriteLine("arr[i]", arr[i], " number to get must be greater or equal than 0");
var n = arr[i] + 1;
var a = new int[n];
arr[0] = 0;
if (arr[i] == 0)
{
a[1] = 1;
}
for ( i = 2; i < n; i++)
{
a[i] = a[i - 2] + a[i - 1];
}
}
}
public static void Main()
{
int[] arr = {7, 8, 3, 9, 11,16,14,91, };
Result(arr);
}
if input is : 1 ,3 ,4 ,6, 7 ,8 10, 11, 15 ,25 output should be: 1, 3, 4, 7, 11 so 1+3=4, 4+3=7 and so on.
I took a look at your code and you were very close.
The biggest issue was you were starting at i = 0 which would cause errors if you attempted to access arr[-1] and arr[-2].
We can solve that by starting with i = 2.
For example:
static int[] Result(int[] arr)
{
int[] result = arr;
for (int i = 2; i < arr.Length; i++)
{
result[i] = result[i-1] + result[i-2];
}
return result;
}
int[] arr = { 1 ,3 ,4 ,6, 7 ,8, 10, 11, 15 ,25 };
arr = Result(arr);
Console.WriteLine(string.Join(", ",arr));
// outputs: 1, 3, 4, 7, 11, 18, 29, 47, 76, 123
Another side note is that unless you're passing the int[] arr as a reference you will need to return a new int[] as the result since Result()'s changes to arr are not reflected on the array.

Two Sum Problem with HashSet not working with duplicates

I am working on an assignment where I have to find pairs of numbers summing up to "x" with average/best O(n) or linear runtime complexity. I can not use brute force as it will increase the complexity.
I am using HashSet and using contains method I am checking If I can find (x - array[i]) and printing it. But contains method checks for the whole HashSet where I want to start that search after "i"th position at each iteration. Also, I can not sort them as I have to print them in an order they appear in the input array.
if (hSet.Contains(x - array[i]))
{
Console.Write("(" + array[i] + "," + (x - array[i]) + ")");
hSet.Add(array[i]);
}
}
With Input array { 1, 6, 3, 2, 5, 5, 7, 8, 4, 8, 2, 5, 9, 9, 1 };
My Output (1,9)(6,4)(3,7)(2,8)(5,5)(5,5)(7,3)(8,2)(4,6)(8,2)(2,8)(5,5)(9,1)(9,1)
Expected output: (1,9), (1,9), (6,4), (3,7), (2,8), (2,8), (5,5), (5,5), (5,5), (8,2), (8,2), (9,1), (9,1)
This code work as your expectation with O(n) complexity (in most of case). Using a Dictionary, not a HashSet.
First, build the dictionary from array with the key is the item, the value is the count of the item.
After that, iterate over items, check it with the dictionary and produce the output. Also reduce the count of this item in the Dictionary to avoid unnecessary output later.
Here is the code:
using System;
using System.Collections.Generic;
class MainClass {
public static void Main (string[] args) {
int[] array = { 1, 6, 3, 2, 5, 5, 7, 8, 4, 8, 2, 5, 9, 9, 1 };
int x = 10;
// build dictionary
Dictionary<int,int> dict = new Dictionary<int,int>();
for(int i=0; i< array.Length; i+=1){
if(dict.ContainsKey(array[i])){
dict[array[i]] += 1;
} else {
dict.Add(array[i], 1);
}
}
// using dictionary
for(int i=0; i< array.Length; i+=1){
if(dict.ContainsKey(x - array[i])) {
int count = dict[x - array[i]];
if(x - array[i] == array[i]){
count -= 1;
}
for(int j = 0; j< count; j+=1 ) {
Console.Write("(" + array[i] + "," + (x - array[i]) + ")");
}
dict[array[i]] -=1;
if(dict[array[i]] == 0){
dict.Remove(array[i]);
}
}
}
Console.WriteLine();
}
}
Here is my easy solution using Dictionary. O(n) time.
namespace TwoSumLeetCode
{
class Program
{
static void Main(string[] args)
{
int[] arr = { 1, 2, 7, 9, 4 };
int target = 13;
Console.WriteLine(TwoSum(arr, target));
Console.ReadLine();
}
// assuming array and target are provided.
public static int[] TwoSum(int[] nums, int target)
{
Dictionary<int, int> dict = new Dictionary<int, int>();
for (int i = 0; i < nums.Length(); ++i)
{
if (dict.ContainsKey(target - nums[i]))
{
return new int[] { dict[target - nums[i]], i };
}
else
{
dict[nums[i]] = i;
}
}
return null;
}
}
}

Passing array value to another array in reverse order

I want to pass int a[] values into int b[]. but I'm facing confusion. Can anyone correct me out. The output of b is 0,0,0,45,4,2,1. it supposed to be like 7,6,5,4,45,2,1.
static void Main()
{
int[] a = new int[] { 1, 2, 45, 4, 5, 6, 7 };
int[] b = new int[7];
int temp = 0;
for (int i = 0; i <= a.Length - 1; i++)
{
b[(b.Length - i) - 1] = a[i];
Console.WriteLine(b[i]);
}
}
The problem here is that you're inserting items starting from the last index of b, but you're outputting them starting from the first index. The code to copy the items is correct, but you need to adjust your line that outputs the result to the console to show the items in b using the same index that you just used to insert the item.
Note there are a couple of other improvments you can make, such as using array initializer syntax for a, using a.Length to instantiate b instead of a hard-coded number, removing the unused temp variable, using i < a.Length for the for condition (instead of i <= Length - 1, which does a subtraction operation on each iteration), and storing the b index in a variable instead of calculating it twice:
static void Main()
{
int[] a = new int[] {1, 2, 45, 4, 5, 6, 7};
int[] b = new int[a.Length];
for (int i = 0; i < a.Length; i++)
{
int bIndex = b.Length - i - 1;
b[bIndex] = a[i];
Console.WriteLine(b[bIndex]);
}
Console.ReadLine();
}
However, this will still output the items in the order in which you insert them, which will be the same order as they appear in a. If you want to show that the items in b are the reverse of a, the easiest way is to do it after you've populated b. Note we can make use of the string.Join method here to join each item with a comma:
static void Main()
{
int[] a = new int[] {1, 2, 45, 4, 5, 6, 7};
int[] b = new int[a.Length];
for (int i = 0; i < a.Length; i++)
{
b[b.Length - i - 1] = a[i];
}
Console.WriteLine($"'a' array: {string.Join(",", a)}");
Console.WriteLine($"'b' array: {string.Join(",", b)}");
Console.ReadLine();
}
Output
If you want to create a reverse array from an existing array, you can use Reverse extension method:
//using System.Linq;
int[] a = new int[] { 1, 2, 45, 4, 5, 6, 7 };
int[] b = a.Reverse().ToArray();
You can learn more about Extension Methods.
You can have this syntax
int[] a = {1, 2, 45, 4, 5, 6, 7};
int[] b = new int[7];
for (int i = 0, j = b.Length - 1; i < a.Length; i++, j--)
{
b[i] = a[j];
Console.WriteLine(b[i]);
}

Wrong number of indices inside []; expected 6

i have a problem regarding my code. I have tried searching on it, but it only confused me more.
I want to split an array(called Array for simplicity) of size 6 in half. one of the halves will move to another array, called Split1
But it gives me an error when trying to move the numbers using a for loop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
int[,,,,,] Array = new int[7, 5, 9, 4, 2, 1];
int[] Split1 = new int[3];
for (int i = 0; i <= Array.Length / 2; i++)
{
Split1[i] = Array[i]; //This is where i get my error
}
}
}
}
If you could point me to the right direction, I would be grateful
This
int[,,,,,] Array = new int[7, 5, 9, 4, 2, 1];
is not an array with 6 elements, this is a 6-dimentional array.
You should define your one dimensional array like this:
int[] Array = new int[] {7, 5, 9, 4, 2, 1};
Additionally, your loop condition is incorrect, you should use < to check upper bound instead of <=:
for (int i = 0; i < Array.Length / 2; i++)
Initialize your array as
int[] Array = new int[6]{7, 5, 9, 4, 2, 1};
What you did before was attempt to create array with 6 dimensions and address one of its cell.
As others pointed out, in loop you want to count from 0 to 2, therefore change <= for <.
You have wrong index with loop
for (int i = 0; i < Array.Length / 2; i++)
{
Split1[i] = Array[i]; //This is where i get my error
}
The way you declare the Array is incorrect, see the following code.
int[] Array = new int[] {7, 5, 9, 4, 2, 1}; // initialization will set the size automatically
int[] Split1 = new int[3];
for (int i = 0; i < 3; i++)
{
Split1[i] = Array[i];
}
1.) You can initialize 1D arrays in many ways :
string[] array = new string[2]; // creates array of length 2, default values
string[] array = new string[] { "A", "B" }; // creates populated array of length 2
string[] array = { "A" , "B" }; // creates populated array of length 2
In your case :
int[] Array = new int[] {7, 5, 9, 4, 2, 1};
2.) Array.Length won't return number of elements inside array. You need Array.Count(). Refer this link for more detail.
for (int i = 0; i <= Array.Count() / 2; i++)
{
Split1[i] = Array[i]; //This is where i get my error
}

How do I find duplicates in an array and display how many times they occurred?

I'm working on a code that prints out duplicated integers from an array with the number of their occurrence. I'm not allowed to use LINQ, just a simple code. I think I'm so close but confused about how to get a correct output:
class Program
{
static void Main(string[] args)
{
int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
int count = 1;
for (int i = 0; i < array.Length; i++)
{
for (int j = i; j < array.Length - 1 ; j++)
{
if(array[j] == array[j+1])
count = count + 1;
}
Console.WriteLine("\t\n " + array[i] + "occurse" + count);
Console.ReadKey();
}
}
}
Since you can't use LINQ, you can do this with collections and loops instead:
static void Main(string[] args)
{
int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
var dict = new Dictionary<int, int>();
foreach(var value in array)
{
// When the key is not found, "count" will be initialized to 0
dict.TryGetValue(value, out int count);
dict[value] = count + 1;
}
foreach(var pair in dict)
Console.WriteLine("Value {0} occurred {1} times.", pair.Key, pair.Value);
Console.ReadKey();
}
Use Group by:
int[] values = new []{1,2,3,4,5,4,4,3};
var groups = values.GroupBy(v => v);
foreach(var group in groups)
Console.WriteLine("Value {0} has {1} items", group.Key, group.Count());
Let's take a look at a simpler example. Let's say we have the array {0, 0, 0, 0}.
What will your code do?
It will first look to see how many items after the first item are equal to it. There are three items after the first that are equal to it.
Then it goes to the next item, and looks for all items after it that are equal to it. There are two. So far we're at 5, and we haven't even finished yet (we have one more to add), but there are only four items in the whole array.
Clearly we have an issue here. We need to ensure that when we've searched the array for duplicates of a given item that we don't search through it again for that same item. While there are ways of doing that, this fundamental approach is looking to be quite a lot of work.
Of course, there are different approaches entirely that we can take. Rather that going through each item and searching for others like it, we can loop through the array once, and add to a count of number of times we've found that character. The use of a Dictionary makes this easy:
var dictionary = new Dictionary<int, int>();
foreach (int n in array)
{
if (!dictionary.ContainsKey(n))
dictionary[n] = 0;
dictionary[n]++;
}
Now we can just loop through the dictionary and see which values were found more than once:
foreach(var pair in dictionary)
if(pair.Value > 1)
Console.WriteLine(pair.Key);
This makes the code clear to read, obviously correct, and (as a bonus) quite a lot more efficient than your code, as you can avoid looping through the collection multiple times.
Here is an answer that avoids using Dictionaries. Since the OP said he is not familiar with them, this might give him a little insight into what Dictionaries do.
The downside to this answer is you have to enforce a limit on the max number in the array, and you can't have negative numbers. You'd never actually use this version in real code.
int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
int[] count = new int[13];
foreach(int number in array) {
// using the index of count same way you'd use a key in a dictionary
count[number]++;
}
foreach(int c in count) {
int numberCount = count[c];
if(numberCount > 0) {
Console.WriteLine(c + " occurs " + numberCount + " times");
}
}
int[] arr = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
var result = arr.GroupBy(x => x).Select(x => new { key = x.Key, val = x.Count() });
foreach (var item in result)
{
if(item.val > 1)
{
Console.WriteLine("Duplicate value : {0}", item.key);
Console.WriteLine("MaxCount : {0}", item.val);
}
}
Console.ReadLine();
Ok I have modified your code. This should do the job:
class Program
{
static void Main(string[] args)
{
int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
for (int i = 0; i < array.Length; i++)
{
int count = 0;
for (int j = 0; j < array.Length; j++)
{
if (array[i] == array[j])
count = count + 1;
}
Console.WriteLine("\t\n " + array[i] + " occurs " + count + " times");
}
Console.ReadKey();
}
}
/This is the answer that helps you to find the duplicate integer values using Forloop and it will return only the repeated values apart from its times of occurences/
public static void Main(string[] args)
{
//Array list to store all the duplicate values
int[] ary = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
ArrayList dup = new ArrayList();
for (int i = 0; i < ary.Length; i++)
{
for (int j = i + 1; j < ary.Length; j++)
{
if (ary[i].Equals(ary[j]))
{
if (!dup.Contains(ary[i]))
{
dup.Add(ary[i]);
}
}
}
}
Console.WriteLine("The numbers which duplicates are");
DisplayArray(dup);
}
public static void DisplayArray(ArrayList ary)
{
//loop through all the elements
for (int i = 0; i < ary.Count; i++)
{
Console.Write(ary[i] + " ");
}
Console.WriteLine();
Console.ReadKey();
}
public static void FindRepeating(int[] input)
{
for (var i = 0; i < input.Length; i++)
{
var abs = Math.Abs(input[i]);
if (input[abs] >= 0)
input[abs] = -input[abs];
else
Console.Write(abs + " ");
}
}
You made a minor mistake of using J instead of i ...
class Program
{
static void Main(string[] args)
{
int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
int count = 1;
for (int i = 0; i < array.Length; i++)
{
for (int j = i; j < array.Length - 1 ; j++)
{
if(array[i] == array[j+1])
count = count + 1;
}
Console.WriteLine("\t\n " + array[i] + "occurse" + count);
Console.ReadKey();
}
}
}
int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 7, 7, 8, 9, 7, 12, 12 };
Dictionary<int, int> duplicateNumbers = new Dictionary<int, int>();
int count=1;
for (int i = 0; i < array.Length; i++)
{
count=1;
if(!duplicateNumbers.ContainsKey(array[i]))
{
for (int j = i; j < array.Length-1; j++)
{
if (array[i] == array[j+1])
{
count++;
}
}
if (count > 1)
{
duplicateNumbers.Add(array[i], count);
}
}
}
foreach (var num in duplicateNumbers)
{
Console.WriteLine("Duplicate numbers, NUMBER-{0}, OCCURRENCE- {1}",num.Key,num.Value);
}
using System;
using System.Collections.Generic;
namespace ConsoleApp1
{
/// <summary>
/// How do you find the duplicate number on a given integer array?
/// </summary>
class Program
{
static void Main(string[] args)
{
int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
Dictionary<int, int> duplicates = FindDuplicate(array);
Display(duplicates);
Console.ReadLine();
}
private static Dictionary<T, int> FindDuplicate<T>(IEnumerable<T> source)
{
HashSet<T> set = new HashSet<T>();
Dictionary<T, int> duplicates = new Dictionary<T, int>();
foreach (var item in source)
{
if (!set.Add(item))
{
if (duplicates.ContainsKey(item))
{
duplicates[item]++;
}
else
{
duplicates.Add(item, 2);
}
}
}
return duplicates;
}
private static void Display(Dictionary<int, int> duplicates)
{
foreach (var item in duplicates)
{
Console.WriteLine($"{item.Key}:{item.Value}");
}
}
}
}
int[] arr = { 1, 2, 3, 2, 4, 5, 2, 4 };
var duplicates = arr.GroupBy(x => x)
.Where(g => g.Count() > 1)
.Select(y => new { Item = y.Key, Count = y.Count() })
.ToList();
Console.WriteLine(String.Join("\n", duplicates));
This approach, fixed up, will give the correct output (it's highly inefficient, but that's not a problem unless you're scaling up dramatically.)
int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
for (int i = 0; i < array.Length; i++)
{
int count = 0;
for (int j = 0; j < array.Length ; j++)
{
if(array[i] == array[j])
count = count + 1;
}
Console.WriteLine("\t\n " + array[i] + " occurs " + count);
Console.ReadKey();
}
I counted 5 errors in the OP code, noted below.
int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
int count = 1; // 1. have to put "count" in the inner loop so it gets reset
// 2. have to start count at 0
for (int i = 0; i < array.Length; i++)
{
for (int j = i; j < array.Length - 1 ; j++) // 3. have to cover the entire loop
// for (int j=0 ; j<array.Length ; j++)
{
if(array[j] == array[j+1]) // 4. compare outer to inner loop values
// if (array[i] == array[j])
count = count + 1;
}
Console.WriteLine("\t\n " + array[i] + "occurse" + count);
// 5. It's spelled "occurs" :)
Console.ReadKey();
}
Edit
For a better approach, use a Dictionary to keep track of the counts. This allows you to loop through the array just once, and doesn't print duplicate counts to the console.
var counts = new Dictionary<int, int>();
int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
for (int i = 0; i < array.Length; i++)
{
int currentVal = array[i];
if (counts.ContainsKey(currentVal))
counts[currentVal]++;
else
counts[currentVal] = 1;
}
foreach (var kvp in counts)
Console.WriteLine("\t\n " + kvp.Key + " occurs " + kvp.Value);
class Program
{
static void Main(string[] args)
{
int[] arr = { 2, 3, 2, 4, 5, 12, 2, 3, 3, 3, 12 };
List<int> nums = new List<int>();
List<int> count = new List<int>();
nums.Add(arr[0]);
count.Add(1);
for (int i = 1; i < arr.Length; i++)
{
if(nums.Contains(arr[i]))
{
count[nums.IndexOf(arr[i])] += 1;
}
else
{
nums.Add(arr[i]);
count.Add(1);
}
}
for(int x =0; x<nums.Count;x++)
{
Console.WriteLine("number:"+nums[x] +"Count :"+ count[x]);
}
Console.Read();
}
}

Categories