I'm trying to return the entire path traced by Djikstra's algorithm using an array but somehow it's returning only the end node, but when i print the value in the same method it's printing correct values.
public int[] PrintPath(int[] path, int j, int src)
{
int[] trace = new int[14];
int i = 0;
if (path[j] == -1)
return path;
PrintPath(path, path[j], src);
Console.Write("{0}", j + 1);
trace[i] = j + 1;
i++;
return trace;
}//PrintPath
source node: 1, destination node: 10
expected output: 1 13 7 9 10
actual array output: 0 10 10 10 10 10 10 10 10 10 10 10 10 10
Your question is definitely not clear.
If you just want to print the path why don't you use String.Join(" ", path) ?
i.e.
int[] path = new int[] {1, 13, 7, 9, 10 };
Console.WriteLine(String.Join(" ", path));
Or please explain well what is your goal.
Related
I have been working on three small programs that extract all the sub-strings of a given string (or even a list of integers) as well as all the different combinations of their elements. I now understand them...
My aim to start like this (originally) was to see if I can solve a puzzle, by learning these programs. Here is the puzzle:
Say I am trekking and I have 6 walking distances { 11, 16, 5, 5, 12, 10 } that I would like to finish within 3 days. So, I can do 11 and 16 kilometers during day 1, 5 and 5 kilometers during day 2, and finally 12 and 10 kilometers during day 3.
Perhaps I could do only 11 kilometers during day 1, 16 and 5 and 5 kilometers during day 2, and 12 and 10 kilometers during day 3.
etc . . . etc . . .
My goal is to work out the "minimum" walked distance over the course of these three days. So, in this example, 11 in day 1 and 26 in day 2 and 22 in day 3 would give a maximum of 26, and that 26 is actually the minimum - it does not get better than this.
No matter what combination of three chunks (days) I choose, the daily walked distance doe not get less than 26. For example, if I choose 11+16 for day 1 and 5+5 for day 2 and 12+10 for days 3, I am looking at a max of 27.
However, I cannot quite figure out how to divide up the list elements in 3, which is the number of days. If it was four, I could have four chunks with arbitrary number of distances in each day. And then add up all the divided elements and see which maximum comes out as minimum.
I appreciate this might be a too-big-a-bite for me at this point (I can just about understand the programs that I have put below) but I was wondering if someone perhaps could help me understand this and help me write a function that can handle any number of days and walking stages.
All I have been able to produce so far is a function that can print all the sub-lists and combinations of these 6 walking stages...
static void Main(string[] args)
{
string str = Console.ReadLine();
for (int i = 1; i <= str.Length; i++)
{
for (int j = 0; j <= (str.Length - i); j++)
{
string subStr = str.Substring(j, i);
Console.WriteLine(subStr);
}
}
Console.ReadLine();
}
static void Main(string[] args)
{
List<int> list = new List<int>() { 11, 16, 5, 5, 12, 10 };
for (int i = 0; i <= list.Count-1; i++)
{
for (int j = 0; j <= list.Count-i; j++)
{
string subList = string.Concat( list.GetRange(i, j) );
Console.WriteLine(subList);
}
}
Console.ReadLine();
}
static void Main(string[] args)
{
GetCombination( new List<int> { 11, 16, 5, 5, 12, 10 } );
Console.ReadLine();
}
static void GetCombination( List<int> list )
{
double count = Math.Pow(2, list.Count);
for (int i = 1; i <= (count-1); i++)
{
string str = Convert.ToString(i, 2).PadLeft(list.Count, '0');
for (int j = 0; j < str.Length; j++)
{
if ( str[j] == '1' )
{
Console.Write( list[j] );
}
}
Console.WriteLine();
}
}
This problem can be solved by dynamic programming. Here is my code for it with top-down approach:
class Program
{
static void Main(string[] args)
{
int[] array = { 11, 16, 5, 5, 12, 10 };
// change last parameter to the number or days
int min = MinDistance(array, 0, 0, 3);
Console.WriteLine(min);
}
static int MinDistance(int[] array, int day, int prevDayDistance, int daysLeft)
{
if (day == array.Length)
{
return prevDayDistance;
}
if (daysLeft == 0)
{
return int.MaxValue;
}
// Keep walking.
int keepWalkResult = MinDistance(array, day + 1, prevDayDistance + array[day], daysLeft);
// Postpone it to the next day.
int sleepResult = MinDistance(array, day, 0, daysLeft - 1);
// Choose the best solution.
return Math.Min(keepWalkResult, Math.Max(prevDayDistance, sleepResult));
}
}
For big input arrays you can consider caching MinDistance results for triples (day,prevDayDistance,daysLeft).
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
In my main I have this array with random numbers
static void Main(string[] args)
{
int [] numbers = new int[] { 1, 6, 4, 11, 2, 5, 9, 3, 7, 10, 12, 8 };
Console.WriteLine("The scores are: ");
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine(numbers[i]);
Console.ReadLine();
}
I need to make a static method in a class that would rearrange these numbers so that they are in order and I'm not sure how to do this. I need to swap these numbers.
Use Array.Sort to sort your original array:
Array.Sort(numbers);
Or Enumerable.OrderBy to create new sorted sequence, which you can save to array:
int[] sorted = numbers.OrderBy(i => i).ToArray();
Array class has a Sort method (Array) which takes array as a parameter.
Sorts the elements in an entire one-dimensional Array using the
IComparable implementation of each element of the Array.
Here am example with LINQPad;
void Main()
{
int [] numbers = new int[] { 1, 6, 4, 11, 2, 5, 9, 3, 7, 10, 12, 8 };
ReturnSortedArray(numbers);
foreach (var element in numbers)
{
element.Dump();
}
}
static void ReturnSortedArray(Array a)
{
Array.Sort(a);
}
Output will be;
1
2
3
4
5
6
7
8
9
10
11
12
To answer the question which was how do I create a static method to sort the Array you can use the code below.
public static void Main(string[] args)
{
int[] numbers = new int[] { 1, 6, 4, 11, 2, 5, 9, 3, 7, 10, 12, 8 };
Console.WriteLine ("The scores are: ");
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine (numbers [i]);
}
Console.WriteLine ("The scores in order are: ");
SortArray (numbers);
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine (numbers [i]);
}
Console.ReadLine ();
}
public static int[] SortArray(int[] arrayIn)
{
Array.Sort (arrayIn);
return arrayIn;
}
OUTPUT
The scores are:
1 6 4 11 2 5 9 3 7 10 12 8
The scores in order are:
1 2 3 4 5 6 7 8 9 10 11 12
you can sort in here
Array.Sort(numbers);
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);
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
http://projecteuler.net/problem=1
If we list all the natural numbers below 10 that are multiples of 3 or
5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the
sum of all the multiples of 3 or 5 below 1000.
If I change "int maxNum" to 10 or any other small number like 20, I'm getting the right answer.
But somehow when I do it with a big number like 1000, it will give me a number which I don't expect to come, I don't know why, please help.
Does it do it because it has reach the max value of an int?
class Program
{
static void Main(string[] args)
{
//TASK: If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
//Find the sum of all the multiples of 3 or 5 below 1000.
int multiplierA = 3;
int multiplierB = 5;
int maxNum = 1000;
int i = 1;
int deelEen = MultiplyFactory(multiplierA, i, maxNum);
int deelTwee = MultiplyFactory(multiplierB, i, maxNum);
int result = deelEen + deelTwee;
Console.WriteLine(result);
Console.Read();
}
static int MultiplyFactory(int multiplier, int i, int maxNum)
{
List<int> savedNumbers = new List<int>();
while(multiplier*i < maxNum)
{
savedNumbers.Add(multiplier*i);
i++;
}
int answer = 0;
foreach(int getal in savedNumbers)
{
Console.WriteLine(getal);
answer = answer + getal;
}
savedNumbers.Clear();
return answer;
}
}
I think the problem is that you need to find sum of all the multiples of 3 OR 5. And what your program is doing is finding sum of all multiplers of 3 + sum of all multipliers of 5.
You can return arrays of int and then sum distinct numbers from arrays.
You can also use Linq to get distinct values from lists
class Program
{
static void Main(string[] args)
{
//TASK: If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
//Find the sum of all the multiples of 3 or 5 below 1000.
int multiplierA = 3;
int multiplierB = 5;
int maxNum = 1000;
int i = 1;
int result = 0;
List<int> deelEen = MultiplyFactory(multiplierA, i, maxNum);
List<int> deelTwee = MultiplyFactory(multiplierB, i, maxNum);
foreach (int val in deelEen)
result += val;
foreach (int val in deelTwee)
if (!deelEen.Contains(val)) result += val;
Console.WriteLine(result);
Console.Read();
}
static List<int> MultiplyFactory(int multiplier, int i, int maxNum)
{
List<int> savedNumbers = new List<int>();
while (multiplier * i < maxNum)
{
savedNumbers.Add(multiplier * i);
i++;
}
return savedNumbers;
}
}
The problem is that you count some numbers twice.
For example you first summ 15 as dividable by 3 and then you add it as dividable by 5.
So for numbers between 1 and 20 you have
deelEen = 3 + 6 + 9 + 12 + 15 + 18
deelTwee = 5 + 10 + 15
and
result = 3 + 5 + 6 + 9 + 10 + 12 + 15 + 15 + 18
when the right answer is
result = 3 + 5 + 6 + 9 + 10 + 12 + 15 + 18
I need to make a function to take in an array of numbers and a target number and return how many different ways you can add or subtract those numbers to get the target number.
ie.
Values = 2, 4, 6, 8 Target = 12
2 + 4 + 6 = 12,
4 + 8 = 12,
6 + 8 - 2 = 12,
2 - 4 + 6 + 8 = 12,
Return 4
Here is what I have so far, but it only counts addition problems.
private void RecursiveSolve(int goal, int currentSum, List<int> included, List<int> notIncluded, int startIndex)
{
for (int index = startIndex; index < notIncluded.Count; index++)
{
int nextValue = notIncluded[index];
if (currentSum + nextValue == goal)
{
List<int> newResult = new List<int>(included);
newResult.Add(nextValue);
mResults.Add(newResult);
}
else if (currentSum - nextValue == goal)
{
List<int> newResult = new List<int>(included);
newResult.Add(nextValue);
mResults.Add(newResult);
}
if (currentSum - nextValue < goal && currentSum - nextValue > 0 )
{
List<int> nextIncluded = new List<int>(included);
nextIncluded.Add(nextValue);
List<int> nextNotIncluded = new List<int>(notIncluded);
nextNotIncluded.Remove(nextValue);
RecursiveSolve(goal, currentSum - nextValue, nextIncluded, nextNotIncluded, startIndex++);
}
if (currentSum + nextValue < goal)
{
List<int> nextIncluded = new List<int>(included);
nextIncluded.Add(nextValue);
List<int> nextNotIncluded = new List<int>(notIncluded);
nextNotIncluded.Remove(nextValue);
RecursiveSolve(goal, currentSum + nextValue, nextIncluded, nextNotIncluded, startIndex++);
}
}
}
Well, the simple way would be to try all of the combinations. If you have N numbers, you have 3^N combinations. The reasoning is this: You sum the numbers but put a coefficient in front of each of them. If your numbers are A1..AN, you add N coefficients (C1..CN) and sum:
Sum (Ai*Ci)
Your Cis can be 1 (meaning you add the number), -1 (meaning you subtract the number) or 0 (meaning you ignore the number).
So, go over all 3^N possible coefficient assignments, calculate the sum and compare to your target.
I am assuming all the numbers are different (as in your example). If a number can appear twice, you need to take that into account.