This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Any chance to get unique records using Linq (C#)?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WaysOf100
{
class WaysOf100Test
{
static void Main(string[] args)
{
WaysOf100 test= new WaysOf100();
test.Go();
test.EliminateDuplicates();
}
}
class WaysOf100
{
List<string> results = new List<string>();
public void Go()
{
int num = 5, temp=0;//to store the intermediate difference
for (int i = 1; i <num; i++)
{
temp = num - i;
for (int j = 1; j <= temp; j++)
{
if (temp % j == 0)
{
//Console.Write(i + " ");
string text = "";
text = i.ToString();
for (int k = 1; k <= (temp / j); k++)
{
//Console.Write(j + " ");
text += j.ToString();
}
char[] rev = text.ToCharArray();
Array.Reverse(rev);
if(!(results.Contains(rev.ToString())))
results.Add(text);
}
}
}
}
public void EliminateDuplicates()
{
//To eliminate the duplicates
/*for (int i = 0; i < results.Count; i++)
{
for (int j = 0; j < results.Count; j++)
{
if (!(results[i].Equals(results[j])))
{
char [] rev = results[j].ToCharArray();
Array.Reverse(rev);
if (results[i]==rev.ToString())
results.Remove(rev.ToString());
}
}
}*/
foreach (var result in results)
{
Console.WriteLine(result);
}
Console.WriteLine("Total number of elements is :{0}",results.Count);
}
}
}
The result so far is
11111
122
14
2111
23
311
32
41
This is what I want in short : the reverse of 41 is 14 and 14 already exists in the list so i don't want to add 41. Similarly, the reverse of 32 is 23 which also exists and hence 32 should not be added. But this piece of could which I've written to achieve the functionality is not giving the desired results
if(!(results.Contains(rev.ToString())))
results.Add(text);
The problem you are having is that rev.ToString()' returns "System.Char[]" and not the string value you wanted/expected. For your logic, try the following:
public void EliminateDuplicates()
{
//Eliminate the duplicates
for (int i = 0; i < results.Count; i++)
{
for (int j = 0; j < results.Count; j++)
{
if (!(results[i].Equals(results[j])))
{
char[] rev = results[j].ToCharArray();
char[] forward = results[i].ToCharArray();
Array.Reverse(rev);
bool bEqual = true;
for( int n = 0 ; n < results[j].Length && true == bEqual ; n++ )
{
if( rev[n] != forward[n] )
{
bEqual = false;
}
}
if( true == bEqual)
results.Remove(results[j] );
}
}
}
foreach (var result in results)
{
Console.WriteLine(result);
}
Console.WriteLine("Total number of elements is : {0} ", results.Count);
}
Solved by myself finally..
if (!(results.Contains(new string(rev))))
results.Add(text);
changed the rev.ToString() as new string(rev) and works fine now. What I want is achieved. Thanks a lot for the help guys
Is reverse the only case you want to check for? One approach would be to canonicalize your results to e.g. sorted order before comparing. So transform both 132 and 213 to 123 before comparing.
Related
using System;
namespace MoveFirst
{
class Program
{
static void Main(string[] args)
{
int[] values = ReadValuesList();
int[] positionsToMove = ReadPositions();
for (int i = 0; i < positionsToMove.Length; i++)
MoveFirst(values, positionsToMove[i]);
PrintValuesList(values);
Console.WriteLine(CheckIfSortedAscending(values));
Console.Read();
}
static bool CheckIfSortedAscending(int[] values)
{
for (int i = 1; i < values.Length; i++)
if (values[i - 1] > values[i])
return false;
return true;
}
public static void MoveFirst(int[] values, int index)
{
var temp = values[0];
values[0] = values[index];
values[index] = temp;
}
static int[] ReadPositions()
{
int positionsNumber = Convert.ToInt32(Console.ReadLine());
int[] positions = new int[positionsNumber];
for (int i = 0; i < positionsNumber; i++)
positions[i] = Convert.ToInt32(Console.ReadLine());
return positions;
}
static int[] ReadValuesList()
{
string[] inputValues = Console.ReadLine().Split(' ');
int[] values = new int[inputValues.Length];
for (int i = 0; i < values.Length; i++)
values[i] = Convert.ToInt32(inputValues[i]);
return values;
}
static void PrintValuesList(int[] valuesList)
{
for (int i = 0; i < valuesList.Length; i++)
Console.Write(valuesList[i] + " ");
Console.Write('\n');
}
}
}
This is my whole code, but I have a problem with the result..Can I get some suggestions how to correct the code within the MoveFirst method ?
There are given a series of numbers on a single line, separated by a space. There are N operations to move a string element to the first position.. Each move is specified on one line (the index of the element which has to be moved to the first position), but all other elements of the string remain in the same order.
For example if the user inputs : 1 2 3 4 5 6
1
5
the result should be : 6 2 1 3 4 5
my result is : 6 1 3 4 5 2
Here is working example, using LinkedList<int>
Input:
1 2 3 4 5 6
2
1
5
Result:
6 2 1 3 4 5
using System;
using System.Collections.Generic;
using System.Linq;
namespace MoveFirst
{
class Program
{
static void Main(string[] args)
{
LinkedList<int> values = ReadValuesList();
int[] positionsToMove = ReadPositions();
for (int i = 0; i < positionsToMove.Length; i++)
MoveFirst(values, positionsToMove[i]);
PrintValuesList(values);
Console.WriteLine(CheckIfSortedAscending(values));
Console.Read();
}
static bool CheckIfSortedAscending(IEnumerable<int> valuesList)
{
var prevValue = int.MinValue;
foreach (int value in valuesList)
{
if (prevValue > value)
return false;
prevValue = value;
}
return true;
}
public static void MoveFirst(LinkedList<int> values, int index)
{
if (index == 0 || index >= values.Count)
return;
var node = values.First;
for (var i = 0; i < index; i++)
node = node.Next;
values.Remove(node);
values.AddFirst(node);
}
static int[] ReadPositions()
{
int positionsNumber = Convert.ToInt32(Console.ReadLine());
int[] positions = new int[positionsNumber];
for (int i = 0; i < positionsNumber; i++)
positions[i] = Convert.ToInt32(Console.ReadLine());
return positions;
}
static LinkedList<int> ReadValuesList()
{
return new LinkedList<int>(Console.ReadLine().Split(' ').Select(Int32.Parse));
}
static void PrintValuesList(IEnumerable<int> valuesList)
{
foreach (int value in valuesList)
Console.Write(value + " ");
Console.Write('\n');
}
}
}
Update:
MoveFirst method for situation when you forced to use array.
public static void MoveFirst(int[] values, int index)
{
if (index == 0 || index >= values.Length)
return;
var temp = values[index];
for (int i = index - 1; i >=0; i--)
values[i + 1] = values[i];
values[0] = temp;
}
This question already has answers here:
Counting the number of times a value appears in an array
(7 answers)
Closed 3 years ago.
I want to write a code in C#.
In fact, I want to write a program in C# such that the program receives a list of numbers and then receives another number and finally check how many times the received number occurs in the given list.
I searched and obtained the following code in C# from GitHub.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Array9a
{
class Program
{
static void Main(string[] args)
{
int i, j,N,count;
Console.WriteLine("Enter the Maximum Range for the Array");
N = Convert.ToInt32(Console.ReadLine());
string[] a = new string[N];
int[] freq = new int[N];
for (i = 0; i < N; i++)
{
a[i] = Console.ReadLine();
freq[i] = -1;
}
for (i = 0; i < N; i++)
{
count = 1;
for (j = i + 1; j < N; j++)
{
if (a[i] == a[j])
{
count++;
freq[j] = 0;
}
}
if (freq[i] != 0)
{
freq[i] = count;
}
}
for (i = 0; i < N; i++)
{
if (freq[i] != 1)
{
Console.Write("{0}{1}", a[i], freq[i]);
}
}
Console.ReadLine();
}
}
}
The output of the mentioned code is the frequency of all elements. But I want to modify the code such that the program receives a number and just check the frequency of the given number.
Recently I am learning C#. Thanks in advance
That seems pretty straight forward.
var result = freq.Count(x => x == theNumberToCheck);
Very simple you can use linq ,for example
int frequency = 1;
int[] arr = new int[] { 1, 4, 6, 7, 1, 2, 6 ,1};
var res =arr.Count(x => x == frequency);
Console.WriteLine(res);//print 3
To get counts of every number:
var distinctValues = theList.Distinct().ToArray();
for(int i = 0; i < distinctValues.Length; i++)
{
var cnt = theList.Count(e => e == distinctValues[i]);
Console.WriteLine($"Element {distinctValues[i]}, count {cnt}");
}
I have a string[] with values like
string[] s = { "saravanan", "Karthick", "Jackson", "saravanan" };
I want to see below output
saravanan occures 2 times
Karthick occures 1 times
Jackson occures 1 times
How can I do this without using List or Dictionary
This is what I have tried so far:
int i, j;
String[] s = {"saravanan", "Karthick", "Jackson", "saravanan"}
Console.WriteLine("Number of Times occured Each Values");
for (i = 0; i < s.Length; i++)
{
int count = 0;
for (j = 0; j < s.Length; j++)
{
if (s[i] == (s[j]))
{
count++;
}
}
Console.WriteLine(s[i]+"is count="+count);
}
That code produces this output:
Number of Times occured Each Values
saravananis count=2
Karthickis count=1
Jacksonis count=1
saravananis count=2
Usually, we solve such problems (querying) via Linq
string[] s = new[] {
"saravanan", "Karthick", "Jackson", "saravanan" };
var result = string.Join(Environment.NewLine, s
.GroupBy(item => item)
.Select(chunk => $"{chunk.Key} occures {chunk.Count()} times"));
Console.Write(result);
In case of nested loops (your current code) we should not print out the same name several times. Let's introduce bool appeared if name has been appeared before
string[] s = new[] {
"saravanan", "Karthick", "Jackson", "saravanan" };
for (i = 0; i < s.Length; i++) {
int count = 0;
bool appeared = false;
for (j = 0; j < s.Length; j++) {
if (s[i] == (s[j])) {
// Names are same. Do we have the name before?
if (j < i) {
// If yes we have no need to loop any more
appeared = true;
break;
}
count++;
}
}
// if name has been appeared already we shouldn't print it out
if (!appeared)
Console.WriteLine(s[i] + "is count=" + count);
}
Since you don't want "saravanan" to appear twice in your output. Then you could use an empty string as a sentinel value. When you find matches that increase the count, blank out that element and have checks in place to skip the element when you run across it later.
using System;
public class Program
{
public static void Main()
{
string[] s = { "saravanan","KArthick","Jackson","saravanan" };
for (int i = 0; i < s.Length; i++)
{
// Skip empty element
if (string.IsNullOrEmpty(s[i]))
{
continue;
}
int count = 1;
for (int j = i + 1; j < s.Length; j++)
{
// Skip empty element
if (string.IsNullOrEmpty(s[i]))
{
continue;
}
if (s[i] == s[j])
{
count++;
// Clear the element to indicate the element as already been counted
s[j] = string.Empty;
}
}
Console.WriteLine("{0} occurs {1} times", s[i], count);
}
}
}
Result
saravanan occurs 2 times
KArthick occurs 1 times
Jackson occurs 1 times
Fiddle Demo
you can use linq group option like this:
String[] s = {"saravanan", "Karthick", "Jackson", "saravanan"};
Console.WriteLine("Number of Times occured Each Values");
var groupArray = s.GroupBy(x => x);
foreach (var group in groupArray)
{
Console.WriteLine(group.Key + "is count=" + group.Count());
}
This question already has an answer here:
Creating all possible arrays without nested for loops [closed]
(1 answer)
Closed 6 years ago.
I posted this similar, previous question, but I was not very clear.
I have the following code:
int N=4;
int[] myArray = new int[N];
for (int i1 = 1; i1 < N; i1++)
myArray[0]=i1;
for (int i2 = 1; i2 < N; i2++)
myArray[1]=i2;
for (int i3 = 1; i3 < N; i3++)
myArray[2]=i3;
for (int i4 = 1; i4 < N; i4++)
{
myArray[3]=i4;
foreach (var item in myArray)
Console.Write(item.ToString());
Console.Write(Environment.NewLine);
}
This outputs the following:
1111
1112
1113
1121
1122
1123
1131
....
3332
3333
Is there a simple way to change this nested for loop to recursion? I am not very skilled at programming, so the simpler, the better. I am not worried about how efficient the code is.
I, effectively, would like to be able to change the int N in my code to different numbers, without having to add or remove anything from my code.
EDIT
Here is what I have so far:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sandbox
{
class Program
{
static void Main(string[] args)
{
int class_length = 4;
int[] toric_class = Enumerable.Repeat(1, class_length).ToArray();
Recursion(toric_class, class_length, 1, 3);
Console.Read();
}
static void Recursion(int[] toric_class, int length, int number, int spot)
{
if (number < 4)
{
toric_class[spot] = number;
foreach (var item in toric_class)
{
Console.Write(item.ToString());
}
Console.Write(Environment.NewLine);
Recursion(toric_class, length, number + 1, spot);
}
}
}
}
This only outputs
1111
1112
1113
I am unsure of where to go from here.
public static void Set(int[] array, int index, int N)
{
if (index == N)
{
foreach (var item in array)
Console.Write(item.ToString());
Console.Write(Environment.NewLine);
return;
}
for (int i = 1; i < N; i++)
{
array[index] = i;
Set(array, index + 1, N);
}
}
And call it this way:
int N = 4;
int[] myArray = new int[N];
Set(myArray, 0, N);
If you want just to simplify and generalize the solition, you don't want any recursion:
// N - length of the array
// K - kind of radix; items of the array will be in [1..K] range
private static IEnumerable<int[]> Generator(int N = 4, int K = 3) {
int[] items = Enumerable
.Repeat(1, N)
.ToArray();
do {
yield return items.ToArray(); // .ToArray() : let's return a copy of the array
for (int i = N - 1; i >= 0; --i)
if (items[i] < K) {
items[i] += 1;
break;
}
else
items[i] = 1;
}
while (!items.All(item => item == 1));
}
Test
string test = string.Join(Environment.NewLine, Generator(4)
.Select(items => string.Concat(items)));
Console.Write(test);
Outcome:
1111
1112
1113
1121
1122
...
3321
3322
3323
3331
3332
3333
I have a list with 10 items in it. I am trying to output to console every possible pairing of 2. But it cannot pair with itself. For example
1,2
1,3
1,4 etc...
I found this to find all possible combinations within a list. Can someone help me modify it please?
private static void GetCombination(IList list)
{
var count = Math.Pow(2, list.Count);
for (var i = 1; i <= count - 1; i++)
{
var str = Convert.ToString(i, 2).PadLeft(list.Count, '0');
for (var j = 0; j < str.Length; j++)
{
if (str[j] == '1')
{
Console.Write(list[j]);
}
}
Console.WriteLine();
}
}
So if you have a list with 1 to 10, you need 1,2 1,3 1,4...1,10 - 2,1 2,3..2,10 and so on.
You just have to use bubble and check if the first index is different from the second.
For more clarification, here is an example:
List<int> mylist = new List<int>(new int[] { 1,2,3,4,5,6,7,8,9 });
GetCombination(mylist);
private static void GetCombination(IList<int> values)
{
for (int i = 0; i < values.Count; i++)
{
for (int j = 0; j < values.Count; j++)
{
if (i != j)
{
Console.WriteLine(values[i] + " " + values[j]);
}
}
}
}
This is such a easy question.Adding to the answer of #FirstOne
you can also return the List containing all the combinations from the function:
List mylist = new List(new int[] { 1,2,3,4,5,6,7,8,9 });
GetCombination(mylist);
public static IList<Tuple<int,int>> GetCombination(IList<int> values)
{
List<Tuple<int,int>> _temp=new List<Tuple<int, int>>();
for (int i = 0; i < values.Count; i++)
{
for (int j = 0; j < values.Count; j++)
{
if (i != j)
{
_temp.Add(Tuple.Create(i, j));
}
}
}
return _temp;
}