Related
I have this loop:
for (int i = 1; i < 10; i++)
But instead I would like to have i for just numbers 1,2,4,5 and 7 and I will hardcode this.
Is there a way I can do this with something like an array?
You could use an array to give the numbers you want like this
int[] loop = new int[] {1,2,4,5,7};
foreach(int i in loop)
Console.WriteLine(i);
Or do it inline which is not as clean when the list of values grows in my opinion
foreach(int i in new int[] {1,2,4,5,7})
Console.WriteLine(i);
foreach (int i in new[] { 1, 2, 4, 5, 7 })
{
}
Basically the answers here are correct, just because you asked explicitly for a for instead of a foreach loop:
int[] loop = new int[] { 1, 2, 4, 5, 7 };
for (int i = 0; i< loop.Length; i++)
{
Console.WriteLine(loop[i]);
}
https://dotnetfiddle.net/c5yjPe
If you want particularly for loop then go with this :
var list = new List<int>() { 1, 2, 4, 5, 7 };
for (int i = 0; i < list.Count; i++) // Loop through List with for
{
Console.WriteLine(list[i]);
}
Obviously the right answer for the general case is to use foreach or an indexed lookup as shown in the other answers, but just for completeness' sake:
You can use any statement within a for expression, including conditionals. With that in mind, it is easy to build a conditional increment or even an exhaustive conditional (state machine?) for a required set:
for (int i = 1; i <= 7; i += (i == 5 || i == 2) ? 2 : 1)
{
Console.Write(i);
}
// Output: 12457
for (int i = 1; i > 0; i = i switch {1=>2, 2=>4, 4=>5, 5=>7, 7=>-1})
{
Console.Write(i);
}
// Output: 12457
Or even something really silly like a self indexing lookup:
for (int i = 1; i > 0; i = new []{0,2,4,0,5,7,0,-1}[i])
{
Console.Write(i);
}
// Output: 12457
I'm trying to move every int in array one "cell" (position) backwards (and take the first int to the last position) in a for loop. (example: if i have array of 5,6,9 the result will be 6,9,5).
Here is my code:
int[] arr = { 1, 2, 3, 4, 5, 6 };
int temp=arr[0];
for (int i=1; i < arr.Length-1; i++)
{
arr[i - 1] = arr[i];
}
arr[arr.Length - 1] = temp;
for (int i = 0; i < arr.Length - 1; i++)
{
Console.WriteLine(arr[i]);
}
Instead of getting
2,3,4,5,6,1
I'm getting
2,3,4,5,5.
Why is my code not working? What is the right way to do such process?
This code does what you need. Sort the array.
int[] arr = { 1, 2, 3, 4, 5, 6 };
//int[] arr = { 5, 6, 9 };
//string[] arr = { "A", "B", "C" };
var result = Enumerable.Range(1, arr.Length).Select(i => arr[i % arr.Length]).ToArray();
foreach (var item in result)
{
Console.WriteLine(item);
}
Input data and Results:
//Input: { 1, 2, 3, 4, 5, 6 };
//Result: 2,3,4,5,6,1
//Input: { 5, 6, 9 };
//Result: 6,9,5
//Input: { "A", "B", "C" };
//Result: B,C,A
Remove the -1 :
for (int i=1; i < arr.Length-1; i++)
in both loops and let the loops run until the end. The condition should be i < arr.Length You never reach the last position.
Although you use arr[arr.Length - 1] to Index the last element, it is different with the loop. If you take a closer look at the finishing condition it says: < that means that i will never get the value of Length - 1 the loop will end one iteration before that. Another way to fix your code would be to change the condition and let i run until it gets this value. You can achieve it by: i <= arr.Length - 1. The little difference should also do the trick. This time the loop will end exactly after I has reached the value of the index of the last element
All you need to do is remove the - 1 from your for loop condition, as it is not iterating over all the elements in your array.
If iterating over an array of 6 elements, the indices are from 0 -> 5. So, for your example, you want your loop to go from index 1 to 5 (what you had been doing is iterating over indices 1-4 (since you were subtracting by 1).
int[] arr = { 1, 2, 3, 4, 5, 6 };
int temp=arr[0];
for (int i=1; i < arr.Length; i++)
{
arr[i - 1] = arr[i];
}
arr[arr.Length - 1] = temp;
for (int i = 0; i < arr.Length; i++)
{
Console.WriteLine(arr[i]);
}
I want to write a program that finds the longest sequence of equal elements in an array of integers. If several longest sequences exist, we should print the leftmost one. e.g. Input: 0 1 1 5 2 2 6 3 3
Output: 1 1
I know that my code doesn't work correctly, but I don't know how to fix it. I should solve the problem using only arrays because I don't know how to use lists.
int[] numbers = Console.ReadLine().Split().Select(int.Parse).ToArray();
for (int i = 0; i < numbers.Length; i++)
{
int[] currentSequenceOfEqualElements = new int[numbers.Length];
for (int j = i + 1; j < numbers.Length; j++)
{
if (numbers[i] == numbers[j])
{
if (currentSequenceOfEqualElements[0] == 0)
{
currentSequenceOfEqualElements[0] = numbers[i];
currentSequenceOfEqualElements[1] = numbers[i];
}
else
{
currentSequenceOfEqualElements[i + 2] = numbers[i];
}
}
else
{
break;
}
}
Console.WriteLine(string.Join(' ', currentSequenceOfEqualElements));
}
I will be very grateful if you can explain to me how to do it.
Here is the solution using the MoreLinq library (https://morelinq.github.io/) that mjwills suggested.
Once you get used to linq and morelinq methods the code is easier to understand than custom algo with nested loops and if.
var numbers = new int[]{ 0, 1, 1, 5, 2, 2, 6, 3, 3};
var result = numbers.GroupAdjacent(x => x)
.MaxBy(x => x.Count())
.FirstOrDefault();
foreach (var i in result)
{
Console.Write($"{i} ");
}
Here's a simple solution, using only loops and no linq. It should be nice and easy to understand.
int[] numbers = new[] { 0, 1, 1, 5, 2, 2, 6, 3, 3 };
// Some variables to keep track of the sequence we're currently looking
// at, and the longest sequence we've found so far. We're going to start
// the loop at the 2nd number, so we'll initialize these as if we've
// already processed the first number (which is 0, so we've seen the
// first number of a sequence of 0's).
// Number of numbers in the current sequence
int count = 1;
// Number which is part of the longest sequence so faar
int longestNum = numbers[0];
// Number of numbers in the longest sequence we've seen so far
int longestCount = 1;
for (int i = 1; i < numbers.Length; i++)
{
// We're starting a new sequence
if (numbers[i] != numbers[i-1])
{
count = 0;
}
count++;
// Have we just found a new longest sequence?
if (count > longestCount)
{
longestCount = count;
longestNum = numbers[i];
}
}
// longestNum = 1 and longestCount = 2 (because the longest sequence
// had 2 1's in it). Turn this into the string "1 1".
Console.WriteLine(
string.Join(" ", Enumerable.Repeat(longestNum, longestCount)));
// If you wanted to end up with an array containing [1, 1], then:
int[] result = new int[longestCount];
Array.Fill(result, longestNum);
I will illustrate a recursive answer for your question, below is the code, I kept some if-else statements that there is no need to have them, but at least the code shows the idea.
The code has a basic method that should be exposed as public and a private recursive method that does the heavy lifting. The longest sequence is the empty array(list)
var longSequenceEqualElem = new List<int>();
Later on the recursion, you pass all the elems of the array through all the recursion calls to keep querying the positions, the pos parameter indicates the position level of the recursion.
if (pos < elems.Length) //stop the recursion here, the position will fall out of the indexes of the array, just return what you have in sequence that should be the longest.
The following statement if (sequence.Contains(elems[pos])) means that you found the same number you were carrying on the sequence in the position pos, so you can add it to the sequence and call the recursion with the adjacent position(pos + 1)
If the element in position pos is not part of the sequence you had, then you need to call the recursion with a new sequence containing elems[pos] and later compare the result of that recursion call with the sequence you had to see which of them is the longest one.
Hope this helps
class Program
{
static void Main(string[] args)
{
var elemts = new int[] { 0, 1, 1, 5, 2, 2, 6, 3, 3 };
var result = LongestSequence(elemts);
foreach (var i in result)
{
Console.Write(i + "\t");
}
Console.ReadLine();
}
public static int[] LongestSequence(int[] elems)
{
var longSequenceEqualElem = new List<int>();
return LongestSequenceRec(elems, longSequenceEqualElem, 0);
}
private static int[] LongestSequenceRec(int[] elems, List<int> sequence, int pos)
{
if (pos < elems.Length)
{
if (sequence.Contains(elems[pos]))
{
sequence.Add(elems[pos]);
return LongestSequenceRec(elems, sequence, pos + 1);
}
else
{
var newSeq = LongestSequenceRec(elems, new List<int> { elems[pos] }, pos + 1);
return (newSeq.Length > sequence.Count) ? newSeq.ToArray() : sequence.ToArray();
}
}
return sequence.ToArray();
}
}
static void Main()
{
int[] array1 = new int[9] {0, 1, 1, 5, 2, 2, 6, 3, 3};
int[] array2 = new int[9] {0, 0, 0, 0, 0, 0, 0, 0, 0};
int max_count = 1;
int tempCount = 1;
int num = 0;
for (int i = 0; i < array1.Length - 1; i++)
{
if (array1[i] == array1[i + 1]) tempCount++;
else tempCount = 1;
if (tempCount > max_count)
{
max_count = tempCount;
num = array1[i];
}
}
for (int i = 0; i < max_count; i++) array2[i] = num;
for (int i = 0; i < max_count; i++) Console.Write(array2[i] + " ");
Console.ReadKey();
}
You have a list of integers, and for each index you want to find the product of every integer except the integer at that index.
i cant understand what is wrong with my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int outcome = 1;
int removed;
List<int> list = new List<int>(new int[] { 1, 2, 6, 4, 6, 4, 9,
8, 3, 1 });
for (int j = 0; j < 9; j++)
{
removed=list[j] ;
list.RemoveAt(j);
for (int i = 0; i < 9; i++)
{
outcome *= list[i];
}
list.Add(removed);
Console.WriteLine(outcome);
}
Console.ReadKey();
}
}
}
I think what's going wrong is that you're defining outcome to be 1 only at the start of the program - as far as I can tell you want to start it inside the first for loop (for (int j = 0; j < 9; j++)).
Would it not be easier to find the product of every integer in the list, and then divide this by the integer at the index?
for (int j = 0; j < 9; j++)
{
outcome = 1;
for (int i = 0; i < 9; i++)
outcome *= list[i];
outcome = outcome / list[j];
Console.WriteLine(outcome);
}
The problem is that you never reset outcome after each iteration, so outcome will just getting bigger and bigger. A simple fix for your program is:
int removed;
List<int> list = new List<int>(new int[] { 1, 2, 6, 4, 6, 4, 9,
8, 3, 1 });
for (int j = 0; j < 9; j++)
{
removed=list[j] ;
list.RemoveAt(j);
int outcome = 1;
for (int i = 0; i < 9; i++)
{
outcome *= list[i];
}
list.Add(removed);
Console.WriteLine(outcome);
}
However, you can improve the efficiency significantly by implement this algorithm (I don't write the cod for you, but you can easily write one yourself)
Compute the products of all element (call it product)
Loop through each element, at each index j, print the value of
product/list[j]
You have two problems:
You are changing the order of the items in the list while you are iterating over them.
You are not resetting outcome to 1 inside the outer loop, so it keeps getting bigger and bigger.
You could consider a different approach:
Compute the product of all the numbers in the list.
For each number in the list, divide the total product by that number to give the product excluding that number.
You should probably use a long to hold the product in the general case, to help avoid overflow (although a long enough list with big enough numbers could still overflow a long).
You can calculate the product using Linq's Aggregate as follows:
List<int> list = new List<int>(new[] {1, 2, 6, 4, 6, 4, 9, 8, 3, 1});
long prod = list.Aggregate(1L, (p, v) => p * v); // 1L means it will use long.
Then you can calculate the product excluding each element of the list as follows:
foreach (var i in list)
Console.WriteLine(prod / i);
Note that this will NOT work if any elements of the list are zero. In that event, every resultant product should be zero.
You must edit for (int i = 0; i < 9; i++) to for (int i = 0; i < list.Count; i++). Because you run list.RemoveAt(j); then list of count is 9;
static void Main(string[] args)
{
int outcome = 1;
int removed;
List<int> list = new List<int>(new int[] { 1, 2, 6, 4, 6, 4, 9,
8, 3, 1 });
for (int j = 0; j < 9; j++)
{
removed = list[j];
list.RemoveAt(j);
for (int i = 0; i < list.Count; i++)
{
outcome *= list[i];
}
list.Add(removed);
Console.WriteLine(outcome);
}
Console.ReadKey();
}
You removing item at index, and adding to end list.
Don't modify list, just skip needed item. For example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestList
{
class Program
{
static void Main(string[] args)
{
double outcome = 1;
List<double> list = new List<double>(new double[] { 1, 2, 6, 4, 6, 4, 9, 8, 3, 1 });
//List<int> list = new List<int>(new int[] { 1, 2, 3 });
for (int i = 0; i < list.Count; i++)
{
for (int j = 0; j < list.Count; j++)
{
if (i == j)
continue;
outcome *= list[j];
}
}
Console.WriteLine(outcome);
Console.WriteLine("Press any key to continue . . .");
Console.ReadKey();
}
}
}
P.S. Use double because the values so high!
There are several problems with your code:
You alterate the list you are looping over
You don't reset your result variable
You don't iterate the whole list (there are ten elements but you only iterate over 9)
A working example could be:
for (int j = 0; j < list.Count; j++)
{
int output = list.Where((val, idx) => idx != j).Aggregate((a, x) => a * x);
Console.WriteLine(output);
}
Console.ReadKey();
How to reverse an array (in C#) without using Array.Reverse() method?
For example,
int[] arr = {1,3,4,9,8};
// some code here
Console.WriteLine(string.Join(",", arr));
should result in
8,9,4,3,1
I got this as an interview task.
The code to be substituted in place of // some code here in the question is:
for (int i = 0; i < arr.Length / 2; i++)
{
int tmp = arr[i];
arr[i] = arr[arr.Length - i - 1];
arr[arr.Length - i - 1] = tmp;
}
You should iterate only through the first half of the array (arr.Length / 2). If you iterate through the whole array (arr.Length), it will be reversed twice, yielding the same element order as before it started.
Basically, you are asked to reimplement Array.Reverse(Array). If you look at how it is implemented in the framework itself and ignore many technical details around, you’ll find that it just calls its three-parameter version (which reverses specified part of an array) on the whole array.
Array.Reverse(Array,Int32,Int32) is a while-loop that swaps elements and maintains two indexes:
i points to the first element of the reversed part, and
j points to the last element of the reversed part.
Rewritten to be substituted in place of // some code here in the question:
int i = 0;
int j = arr.Length - 1;
while (i < j)
{
var temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
This is easier to grasp than the implementation using for-loop, does less arithmetic and elegantly evades the gotcha with double reversion.
That is So Simple Start loop from Array legth and so on watch code and you will get understand :)))
int[] arr = new int[5] { 1, 2, 3, 4, 5 };
for (int i = arr.Length-1; i >= 0; i--)
{
Console.WriteLine(arr[i]);
}
int[] arr1 = {1,3,4,9,8};
int[] arr2 = new int[5];
int j = 0;
for(int i = arr1.Length - 1; i >= 0; i--)
{
arr2[j] = arr1[i];
j++;
}
for (int i = 0; i < array.Length - i; i++)
{
var value = array[array.Length - i - 1];
array[array.Length - i - 1] = array[i];
array[i] = value;
}
Well, obviously you can just copy to a new array, in reverse order.
To do the operation "in place", you can work from both ends towards the middle: Load the first and last elements, then store them back, the first into the last location, and the last into the first location. Then do the second and the next-to-last, etc. If you have an even number of elements you do N/2 iterations. If an odd number you do (N-1)/2 iterations and leave the middle element where it was.
There are probably other algorithms that would be marginally faster when considering cache line size and other memory characteristics, but they wouldn't be worth it unless you were in a really performance-critical situation.
// without using Reverse method and without using additional array
// try yield operator starting from the last element
public IEnumerable<int> Reverse (int[] array)
{
for (int i = array.Length - 1; i >= 0; i--) {
yield return array [i];
}
}
char[] strx = { '1','2','3','4','5','6','7','8','9' };
int i = strx.Length;
string ktr ="";
while (i>0)
{
i--;
ktr += strx[i];
if (i==0)
{
i = strx.Length;
while (i > 0)
{
i--;
strx[i] = ktr[i];
}
}
}
int j;
Console.WriteLine("Array strx in reverse order: ");
for (j = 0; j < strx.Length; j++ )
{
Console.Write("{0}", strx[j]);
}
try something like:
var counter = 1;
var newArr = new int[arr.length];
for(int i = 0; i < arr.length; i++)
{
newArr[i] = arr[arr.length - counter];
counter++;
}
I didn't test that but it should be on the right track. Any reason you dont want to use Array.Reverse? Its probably a well-optimized version of the algorithm.
You can do this in many ways, from the most fast to the most stupid like:
int[] arr = new int[] { 1,2,3 };
arr = (from a in arr orderby a descending select a).ToArray();
But I cannot understand why are you pursuing such a futile quest, if that is to impress someone somewhere then use this instead of the for loops :)
I am not good at loops at all. But this is what seems simple to me -
int[] array1 = { 1, 2, 3, 4, 5 };
int[] reverseArray = new int[array1.Length];
for (int i = 0; i <= array1.Length - 1; i++)
{
reverseArray[i] = array1[array1.Length - i - 1];
}
This is the dynamic solution for reversing the array of any datatype.Some of the key points in my algorithm is first calculate the half of array length and add check to stop iteration when array indexes have same value.The stage having same indexes depict that it start the reverse operation again.So at this stage break the outer loop by using "goto Statement".
string[] unreversed = {"A","B","C","D","E","F","G","H","I","J","K"};
int q=unreversed.Length;
int t = q / 2;
var temp1 = "A";
for(int i = 0;i<unreversed.Length;i++)
{
q = q - 1;
for(int k=q;k<=q;k++)
{
if (unreversed[k] != unreversed[i] && i!=t)
{
temp1 = unreversed[i];
unreversed[i] = unreversed[k];
unreversed[k] = temp1;
}
else
{
goto printarray;
}
}
}
printarray:
foreach (var k in unreversed)
{
Console.WriteLine(k);
}
//Create temp array with the same size.
int[] arrTemp = new int[arr.Length];
int i = 0;
//Assign last value of arr to first value of arrTemp
for (int j = arr.Length - 1; j >= 0; j--)
{
arrTemp[i] = arr[j];
i++;
}
arr = arrTemp;
I prefer a LINQ expression that uses an index:
using System.Linq;
int[] arr = { 1, 3, 4, 9, 8 };
arr = arr.Select((n, idx) => new {n, idx})
.OrderByDescending(r => r.idx)
.Select(r => r.n).ToArray();
public int[] Reverse(params int[] numbers)
{
for (int i = 0; i < numbers.Length / 2; i++)
{
int tmp = numbers[i];
numbers[i] = numbers[numbers.Length - i - 1];
numbers[numbers.Length - i - 1] = tmp;
}
return numbers;
}
Here is an example of reversing an array using the Length() function and a simple for loop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
int[] arr = new int[] {4, 8, 2, 9, 5, 5};
int length = arr.Length;
for(int i = 0; i < arr.Length; i++)
{
Console.WriteLine(arr[length-1] + " ");
length = length - 1;
}
}
}
}
You can try this, Without using additional temporary variable:
for(int i = left; i < right/2; i++)
{
(nums[i], nums[right - i - 1]) = (nums[right - i - 1], nums[i]);
}
Stack stack=new Stack;
var newArr = new int[arr.length];
for(int i = 0; i < arr.length; i++)
{
stack.push(arrr[i])
}
for(int i = 0; i < arr.length; i++)
{
newarr[i]= stack.pop()
}
int[] array1 = { 1, 2, 3, 4, 5 };
for (int x = 4; x < array1.Length && x != -1; x--)
{
int tmp;
tmp=array1[x];
Console.Write("{0} ", tmp);
}
That's my solution for this.
It is better to use Array.Reverse method
int[] arr ={1,3,4,9,8};
Array.Reverse(arr);
You can read more description Here
int[] triangles = new int[]{0,1,2,3}
for (int j = triangles.Length; j > (triangles.Length / 2); j--)
{
var temp = triangles[j - 1];
triangles[j - 1] = triangles[triangles.Length - j];
triangles[triangles.Length - j] = temp;
}
I would prefer to reverse an array from the end of it. My solution's above.
Console.WriteLine("Enter a string");
string input = Console.ReadLine();
string s = "";
for (int i = input.Length-1 ; i >= 0; i--)
{
s = s + input[i];
}
Console.WriteLine(s);
function printReverse(arr) {
for(var i = arr.length - 1; i >= 0; i--){
console.log(arr[i]);
}
}
printReverse([1, 2, 3, 6, 47, 88]);
function printReverse(arr) {
for (var i = arr.length - 1; i >= 0; i--) {
console.log(arr[i]);
}
}
printReverse([1, 2, 3, 6, 47, 88])
Can do this with single for loop..
int[] arr ={1,3,4,9,8};
for(int i=arr.length-1;i>=0;i--)
{
Console.Write(arr[i]);
}
You can just loop backwards:
int[] arr= new int[] {1, 2, 3, 4, 6};
for(int i=arr.Length-1 ;i>= 0 ; i--)
{
Console.WriteLine(arr[i].ToString());
}