How to automatically feed in lines to a .NET application - c#

I have an application whose entry point is like
static void Main(String[] args)
{
int T = Int32.Parse(Console.ReadLine());
for (int t = 0; t < T; ++t)
{
int[] line = Array.ConvertAll(Console.ReadLine().Split(' '), Int32.Parse);
int N = line[0], M = line[1];
char[,] matrix = new char[M, N];
for (int i = 0; i < N; ++i)
{
char[] row = Console.ReadLine().Where(c => c != ' ').ToArray();
for (int j = 0; j < M; ++j)
matrix[j, i] = row[j];
}
int K = Int32.Parse(Console.ReadLine());
var ff = new ForbiddenForest(matrix);
Console.WriteLine(K == ff.OptimalMoveNumbers ? "Impressed" : "Oops!");
}
}
and I have test input like
3
2 3
*.M
.X.
1
4 11
.X.X......X
.X*.X.XXX.X
.XX.X.XM...
......XXXX.
3
4 11
.X.X......X
.X*.X.XXX.X
.XX.X.XM...
......XXXX.
4
which I need to debug and which I don't want to manually type in to the console line-by-line. What would be the easiest way to feed this in to the program? Is there a way of writing batch file that would run ThisProgram.exe and feed it my test input?

Assuming you use Visual Studio as your development IDE:
You can feed input to your application for Debug purposes by putting these input in Project Properties > Debug > Command line arguments.

You can loop through a file with the for-loop in batch:
for /f "delims=" %%g in (yourInputFile.txt) do (
ThisProgram.exe %%g
)
Also make sure, yourInputFile.txt is placed in the same directory as the batchfile and ThisProgram.exe . If they are not in the same directory you will have to change the directory using cd path\to\files

Related

How to print numbers in a 2D array in c#?

i have made a 2D array in c#. I want have a method to fill in some numbers and a method to print it. But this doesnt work. Since it is for school. The static void main cant be changed. Can anyone help me? the if statement is true and will say invalid number of arguments here is some code:
static void Main(string[] args)
{
if (args.Length != 2)
{
Console.WriteLine("invalid number of arguments!");
Console.WriteLine("usage: assignment[1-3] <nr of rows> <nr of columns>");
return;
}
int numberOfRows = int.Parse(args[0]);
int numberOfColumns = int.Parse(args[1]);
Program myProgram = new Program();
myProgram.Start(numberOfRows, numberOfColumns);
}
void Start(int numberOfRows, int numberOfColumns)
{
int[,] matrix = new int[numberOfRows, numberOfColumns];
InitMatrix2D(matrix);
DisplayMatrix(matrix);
}
void InitMatrix2D(int[,] matrix)
{
int numberPlusOne = 1;
for (int rows = 0; rows < matrix.GetLength(0); rows++)
{
for (int columns = 0; columns < matrix.GetLength(1); columns++)
{
matrix[rows, columns] = numberPlusOne++; // telkens vullen met +1
}
}
}
void DisplayMatrix(int[,] matrix)
{
for (int rows = 0; rows < matrix.GetLength(0); rows++)
{
for (int columns = 0; columns < matrix.GetLength(1); columns++)
{
Console.Write($"{matrix[rows, columns]}");
}
}
}
The if statement is true.
It may not be obvious, but the array of strings passed to Main(string[] args) — args — are the arguments passed to the program on the command line, aptly called command line arguments. If you start a C# program named, say, myprog from a Console window with myprog 1 2 3, the operating system and .net runtime see to it that args will have (typically) four elements, namely "myprog", "1", "2" and "3". Perhaps the first one is missing and it's only "1", "2" and "3"; that seems to be the case when I try it on Windows 10 and .net 5.0.
You have probably never started your (or maybe any) program from the command line, hence your confusion.
In order to start a custom program which is not in the program search path from the Console, you need to know where it is because you either cd there or type the entire path name. The program may not be easy to find if you work with an IDE like Visual Studio.1
But Visual Studio allows you to pass arguments to the program via the project's properties dialog. Right-click the project, click Properties at the bottom, choose "Debug" on the left and enter two numbers in the "Application arguments" text box. Then hit F5 if you have a Debug build configuration active.
As an aside:
It is customary to return from Main with a non-zero value if the program encounters an error. That return value is used as the exit status of the program, which can be inspected by the caller. The wrong number of arguments is a very basic error condition that should be diagnosable: A script may choose not to continue when a critical step in a processing chain failed. It would be better to declare Main to return int. That way you can return non-zero when an error is encountered. Since you cannot change Main, this is perhaps a note to your teacher (who will likely answer that he doesn't want to complicate matters ;-) ).
It is customary to make error output on standard error, not on standard out. The reason is that a caller may parse the standard output (perhaps output from a chain of programs, not only yours!) and would be confused by unexpected text in the standard output. It would be better to write Console.Error.WriteLine("invalid number of arguments!");.
1 You can right-click the editor tab of a source file in Visual Studio and click "open containing folder"; somewhere below that project folder is an exe file, simply search *.exe in the explorer that opened. Right-click the entry with your exe and choose "open file location", then shift-right-click that folder and choose "open cmd window here", or the powershell equivalent.
Whew.
Now, if your program is named program.exe, type program 5 7 or whatever values you desire, and it should work.
Here are two different ways to display a matrix
1,2,3,4,5
6,7,8,9,10
11,12,13,14,15
16,17,18,19,20
21,22,23,24,25
26,27,28,29,30
31,32,33,34,35
| 1 2 3 4 5|
| 6 7 8 9 10|
| 11 12 13 14 15|
| 16 17 18 19 20|
| 21 22 23 24 25|
| 26 27 28 29 30|
| 31 32 33 34 35|
The first way is like a CSV file, with comma-separated values for each row. It is still human-readable but primarily targeted toward file operations.
The second way is arranged in a table/grid which far more human-readable, but less readable by computers.
The code to generate the above two styles is declared using extension methods, DisplayDelimited() and DisplayTable()
public static class DisplayExtensions
{
public static string DisplayDelimited<T>(this T[,] matrix, string columnSeparator = ",")
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
if (j > 0)
{
sb.Append(columnSeparator);
}
sb.Append(matrix[i, j]);
}
sb.AppendLine();
}
return sb.ToString();
}
public static string DisplayTable<T>(this T[,] matrix, int columnWidth = 8, string bracketSymbol = "|")
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < matrix.GetLength(0); i++)
{
sb.Append(bracketSymbol);
for (int j = 0; j < matrix.GetLength(1); j++)
{
if (j > 0)
{
sb.Append(" ");
}
sb.Append(matrix[i, j].ToString().PadLeft(columnWidth));
}
sb.AppendLine(bracketSymbol);
}
return sb.ToString();
}
}
class Program
{
static void Main(string[] args)
{
int value = 0;
int[,] matrix = new int[7, 5];
for (int i = 0; i < 7; i++)
{
for (int j = 0; j < 5; j++)
{
matrix[i, j] = ++value;
}
}
Console.WriteLine(matrix.DisplayDelimited());
Console.WriteLine(matrix.DisplayTable());
}
}

C# string.split is splitting letter by letter when pulled from IBM Emulator

I work in an IBM emulator environment. I'm trying to grab a row of text and split by spaces to return each word in the row. However, when printed to the console it's showing only first letters. This code has worked in the past when utilized on raw text or api results. The same code when implemented on an IBM Emulator does not however.
For example if the row from the emulator is HEALTHSELECT OF TEXAS , the code below would do the first and second console print correctly. With the double for-loop printing only the first letters. The real listed console output is below:
looking for healthselect of texas in away from home care
healthselect
of
texas
looking for h in a
looking for h in w
looking for h in a
looking for h in y
looking for e in a
looking for e in w
looking for e in a
looking for e in y
looking for a in a
looking for a in w
looking for a in a
looking for a in y
C# code:
public bool inStringAll(string needle, string haystack)
{
needle = Regex.Replace(needle.ToLower(), #"\r\n", string.Empty);
haystack = Regex.Replace(haystack.ToLower(), #"\r\n", string.Empty);
Console.WriteLine($"looking for {needle} in {haystack}");
string[] needleArr = needle.Split(' ');
string[] haystackArr = haystack.Split(' ');
for(int j = 0; j < needleArr.Length; j++)
Console.WriteLine(needleArr[j]);
int percent = 0;
int increment;
bool decision = false;
if (needleArr.Length > 3)
increment = 100 / 3;
else increment = 100 / needleArr.Length;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < haystackArr.Length; j++)
{
Console.WriteLine("looking for " + needle[i] + " in " + haystack[j]);
if (needleArr[i] == haystackArr[j])
{
percent += increment;
}
}
}
Console.WriteLine($"Percent: {percent}%");
if (percent >= 50)
decision = true;
return decision;
}
Has anyone worked with an emulator of this kind and had any issues getting these values correctly? I've worked with old attachmate systems using EXTRA! Basic and there was no issues, but this is my first client with IBM systems using C#.net so it may be different.

Why does my C# code does not work as intended (arrays transformation, newbie)

I'm trying to take array of numbers (0 or 1 only) and repeatedly transform it as follows:
first and last numbers are always 0;
all the other numbers are
derived from previous state of array: if array[n] and its two neighbours
(array[n-1], array[n] and array[n+1]) have the same value (three 0s or three 1s) then newarray[n] should be be 1, otherwise it should be 0 (that produces nice patterns).
For example, if the array size is 10 and it starts with all zeroes, then program should output this:
0000000000
0111111110
0011111100
0001111000
0100110010
0000000000
0111111110
...and so on
I wrote a code that should do this and it doesn't work as intended. It always does first transformation perfectly but then begins some wrong, asymmetric, crazy stuff:
0000000000
0111111110
0000000000
0101010100
0000000010
0101010000
What makes my code behave the way it does?
Here is the code:
namespace test
{
class Program
{
public static void Main(string[] args)
{
const int leng = 10; //length of array
int[] arrayone = new int[leng];
int[] arraytwo = new int[leng];
for (int i = 0; i<=leng-1; i++)
{
arrayone[i] = 0;
arraytwo[i] = 0;
} //making two arrays and filling them with zeroes
for (int i = 0; i<=leng-1; i++)
{
Console.Write(arrayone[i]);
}
Console.WriteLine(' '); //printing the first state of array
for (int st=1; st<=16; st++) //my main loop
{
arraytwo[0]=0;
arraytwo[leng - 1]=0; //making sure that first and last elements are zero. I'm not sure I need this since I fill both arrays with zeroes in the beginning. But it probably doesn't hurt?
for (int i = 1; i<=leng-2; i++) //calculating new states for elements from second to second-to-last
{
if (((arrayone[i-1]) + (arrayone[i]) + (arrayone[i+1]) == 0) | ((arrayone[i-1]) + (arrayone[i]) + (arrayone[i+1]) == 3) == true)
arraytwo[i] = 1;
else
arraytwo[i] = 0;
}
//by now arraytwo contains transformed version of arrayone
for (int i = 0; i<=leng-1; i++)
{
Console.Write(arraytwo[i]);
} //printing result
arrayone = arraytwo; //copying content of arraytwo to arrayone for the next round of transformation;
Console.WriteLine(' ');
}
Console.Write(" ");
Console.ReadKey(true);
}
}
}
Tweakable version: https://dotnetfiddle.net/8htp9N
As pointed out you're talking an object and working on it, at the end of that you're assigning the reference not the values. one way to combat that would be
for your line: arrayone = arraytwo;
change it to : arrayone = (int[])arraytwo.Clone();
this will copy the values - for integers this will be sufficient.
Please, notice how your current code is complex and thus diffcult to debug. Make it simpler, extract a method:
using System.Linq;
...
private static IEnumerable<int[]> Generate(int width) {
int[] item = new int[width];
while (true) {
yield return item.ToArray(); // .ToArray() - return a copy of the item
int[] next = new int[width];
for (int i = 1; i < item.Length - 1; ++i)
if (item[i - 1] == item[i] && item[i] == item[i + 1])
next[i] = 1;
item = next;
}
}
Then you can put
public static void Main(string[] args) {
var result = Generate(10) // each line of 10 items
.Take(7) // 7 lines
.Select(item => string.Concat(item));
Console.Write(string.Join(Environment.NewLine, result));
}
Outcome:
0000000000
0111111110
0011111100
0001111000
0100110010
0000000000
0111111110

Different program outputs when different capacity arguments are passed to List constructor, C#

I'm implementing a slightly fancier version of counting sort in C#. The "slightly fancier" part is that I replace some elements in the sorted output with "-" rather than the original value. Here is a sample input/ output pair (the range of possible integer values are between 0 and 99):
IN
20
0 ab
6 cd
0 ef
6 gh
4 ij
0 ab
6 cd
0 ef
6 gh
0 ij
4 that
3 be
0 to
1 be
5 question
1 or
2 not
4 is
2 to
4 the
OUT
- - - - - to be or not to be - that is the question - - - -
And here is my implementation:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution
{
static void Main(String[] args)
{
int n = Convert.ToInt32(Console.ReadLine());
List<List<string>> rsltLists = new List<List<string>>(100);
for(int i=0; i<n; i++)
{
rsltLists.Add(new List<String>()); // PROBLEM IS HERE
}
for(int a0 = 0; a0 < n; a0++)
{
string[] tokens_x = Console.ReadLine().Split(' ');
int x = Convert.ToInt32(tokens_x[0]);
string s = tokens_x[1];
if(a0 < n/2)
{
// Replace string with '-'
rsltLists[x].Add("-");
}
else
{
rsltLists[x].Add(s);
}
}
foreach(List<string> rsltList in rsltLists)
{
foreach(string rslt in rsltList)
{
Console.Write(rslt + " ");
}
}
}
}
I'm submitting my code as the solution to a problem on Hackerrank. The problem is that for the 5th test case, my solution times out (the test case contains an enormous number of lines so I'm not including it here). To speed my solution up, I replaced the //PROBLEM IS HERE line with rsltLists.Add(new List<String>(100)). This causes the 5th test case to fail rather than time out (test cases 1-4 still passed). When I replaced the problem line with rsltLists.Add(new List<String>(10000)) the 5th test case and several other test cases failed (though not all of the test cases failed). Why would changing the amount of space I reserve for each List<String> cause this inconsistent behavior? I would expected the fifth test case to fail (maybe), but I wouldn't have expected test cases that were passing previously to start failing.
Why are you creating n rsltLists? That is not the requirement. There are 100 possible values and array is better for that. You should NOT be using n here. x is 100.
for(int i=0; i<n; i++) // no, problem is here
{
rsltLists.Add(new List<String>()); // PROBLEM IS HERE
}
This should be pretty fast
public static string HackerSort()
{
List<string> input = new List<string>() {"20"
, "0 ab"
, "6 cd"
, "0 ef"
, "6 gh"
, "4 ij"
, "0 ab"
, "6 cd"
, "0 ef"
, "6 gh"
, "0 ij"
, "4 that"
, "3 be"
, "0 to"
, "1 be"
, "5 question"
, "1 or"
, "2 not"
, "4 is"
, "2 to"
, "4 the" };
List<string>[] wl = new List<string>[100];
int n = int.Parse(input[0]);
int half = n/2;
char split = ' ';
for (int i = 0; i < n; i++)
{
string s = input[i + 1];
string[] ss = s.Split(split);
//Debug.WriteLine(ss[0]);
int row = int.Parse(ss[0]);
if(wl[row] == null)
{
wl[row] = new List<string>((n / 100) + 1);
}
wl[row].Add(i < half ? "-" : ss[1]);
}
StringBuilder sb = new StringBuilder();
foreach(List<string> ls in wl.Where(x => x != null))
{
sb.Append(string.Join(" ", ls) + ' ');
}
Debug.WriteLine(sb.ToString().TrimEnd());
return sb.ToString().TrimEnd();
}
Couple thoughts on this:
You're creating a list for each option... but many aren't used. How about only instantiating the lists that you'll actually use?
Compounded with the one above, you're creating 100 lists, each with a capacity of 100... that's a lot of memory to set aside that you won't be using
One solution:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
class Solution
{
static void Main(String[] args)
{
int n = Convert.ToInt32(Console.ReadLine());
int threshold = n / 2;
List<string>[] stringMap = new List<string>[100];
for(int a0 = 0; a0 < n; a0++){
string[] tokens_x = Console.ReadLine().Split(' ');
int x = Convert.ToInt32(tokens_x[0]);
if(stringMap[x] == null)
{
stringMap[x] = new List<string>();
}
stringMap[x].Add((a0 >= threshold ? tokens_x[1] : "-"));
}
List<string> output = new List<string>();
for(int i = 0; i < stringMap.Length; i++)
{
if(stringMap[i] == null)
{
continue;
}
output.AddRange(stringMap[i]);
}
Console.WriteLine(string.Join(" ", output));
}
}
The "inner" List will always have exactly two elements, one of which you want to treat as a number rather than a string. Better to use a small class or even a tuple here, rather than nested lists.
I'm at work with only VS2015 with no tuple support, so this code is unchecked and likely has a mistake or two:
static void Main(String[] args)
{
int n = int.Parse(Console.ReadLine());
var data = new List<(int, string)>(n);
for(int a0 = 0; a0 < n; a0++)
{
var tokens = Console.ReadLine().Split(' ');
int x = int.Parse(tokens[0]);
if(a0 < n/2) tokens[1] = "-";
data.Add( (val: x, str: tokens[1]) )
}
foreach(var item in data.OrderBy(i => i.val))
{
Console.Write(item.str + " ");
}
}
One way to solve the memory-hogging / long processing times would be to store the input in a SortedDictionary<int, List<string>> instead. The Key would be the integer portion of the input, and the Value would be a List<string> containing the other part of the input (one item per input that matches the key).
Then, when we have the dictionary populated, we can just output each List<string> of data in order (the SortedDictionary will already be sorted by Key).
In this way, we're only creating as many lists as we actually need, and each list is only as long as it needs to be (both of which I believe were causes for the errors in your original code, but I don't know where to find the actual test case code to verify).
private static void Main()
{
var length = Convert.ToInt32(Console.ReadLine());
var halfway = length / 2;
var items = new SortedDictionary<int, List<string>>();
for (int inputLine = 0; inputLine < length; inputLine++)
{
var input = Console.ReadLine().Split();
var sortIndex = Convert.ToInt32(input[0]);
var value = inputLine < halfway ? "-" : input[1];
if (items.ContainsKey(sortIndex)
{
items[sortIndex].Add(value);
}
else
{
items.Add(sortIndex, new List<string> {value});
}
}
Console.WriteLine(string.Join(" ", items.SelectMany(i => i.Value)));
// Not submitted to website, but for local testing:
Console.Write("\n\nPress any key to exit...");
Console.ReadKey();
}
Output

c# Hackerrank code terminated due to time out but there is no way to optimize this code further?

I was doing a hacker rank challenge in c# to try and bring some of my c skills over to c#. Now I know hacker rank is notoriously stupid with killing programs due to time out (in this case if it lasts more than 3 seconds). But I honestly cannot think of a way to optimize this code further.
Here are the instructions:
https://www.hackerrank.com/challenges/ctci-array-left-rotation
Basically the challenge is to shift an array of numbers some x amount of times over in the left direction inside the array.
To my knowledge this code is as minimal as it can get and still do the thing they requested. The only way I can think to optimize this code further is to merge the constraint "if(a[i] > 1000000 || a[i] < 1 )" with the writeline forloop at the end of the code, but I tried that and it didn't work.
To me this is literally the minimum number of operations to move the array over by an amount x. But the code fails in test case 7 and 8 (out of 8) due to time out. Am I missing something?
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution
{
static void Main(String[] args)
{
int i, j;
int temp = 0;
string[] tokens_n = Console.ReadLine().Split(' ');
int n = Convert.ToInt32(tokens_n[0]);
int k = Convert.ToInt32(tokens_n[1]);
string[] a_temp = Console.ReadLine().Split(' ');
int[] a = Array.ConvertAll(a_temp,Int32.Parse);
//constraints
if(n >= 100000 || n < 1 )
{
System.Environment.Exit(1);
}
if(k > n || n < 1 )
{
System.Environment.Exit(1);
}
for(i = 0; i< n; i++)
{
if(a[i] > 1000000 || a[i] < 1 )
{
System.Environment.Exit(1);
}
}
//double for loop. one adjust position by one. then repeat k number of times.
for(j = 0; j<k; j++)
{
for(i = 0; i< n-1; i++)
{
temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
}
}
//view array
for(i = 0; i< n; i++)
{
Console.Write(a[i] + " " );
}
}
}
I used a queue mechanism to get this working. That way you don't have to do any array copy and just rotating the string to the end.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution {
static int[] leftRotation(int[] arr, int rotation) {
Queue<int> queue = new Queue<int>(arr);
for (int i = 0; i < rotation; i++)
{
queue.Enqueue(queue.Dequeue());
}
return queue.ToArray();
}
static void Main(String[] args) {
string[] tokens_n = Console.ReadLine().Split(' ');
int n = Convert.ToInt32(tokens_n[0]);
int d = Convert.ToInt32(tokens_n[1]);
string[] a_temp = Console.ReadLine().Split(' ');
int[] a = Array.ConvertAll(a_temp,Int32.Parse);
int[] result = leftRotation(a, d);
Console.WriteLine(String.Join(" ", result));
}
}
Shuffling the values one at a time is very slow. There is no need to do this. One can think of the rotation as moving 2 blocks - the values to the left of the rotation point and the values including and to the right of the rotation point
1 2 3 4 5 6 7 8 9
Rotate this 3 times is
move 1-3 to a temp variable
move 4-9 to the start of the array
move 1-3 to the end of 4-9
Edit: Add a bit more detail
We want to rotate the array 3 places.
move 1 2 3 to a temporary array
1 2 3
1 2 3 4 5 6 7 8 9
move 4-9 to the start of the array
1 2 3
4 5 6 7 8 9 7 8 9
move 1-3 to the end of the array
1 2 3
4 5 6 7 8 9 1 2 3
We can get away without the temp array for the left hand block if we create a new target array and copy everything to it. The following passes all the tests for the problem
var result = new int[a.Length];
var block2Length = a.Length - k;
Array.Copy(a, k, result, 0, block2Length);
Array.Copy(a, 0, result, block2Length, k);
Console.WriteLine(string.Join(" ", result.Select(v => v.ToString())));
Other Points
The constraints in HackerRank are part of the problem definition - they are telling us what the values can/will do so that we don't have to worry about solving a more general problem
e.g.
1 <= a[i] < 10^6
tells us the numbers will all be within the range for standard integers, no need to use long or BigInteger. As part of the solution we don't need to confirm these. In a real world situation different rules apply but here we have as much code checking values that cannot be wrong as we have solving the problem.
This has already been answered but there is a different solution that is very fast:
The idea is that you use the periodicity of the shifting. Shifting an element n+1 times is the same as shifting it 1 time which boils down to k % n.
Thus, you can simply create a new array and move the "old" elements directly to the correct spot. See the sample code below:
static void Main(String[] args) {
string[] tokens_n = Console.ReadLine().Split(' ');
int n = Convert.ToInt32(tokens_n[0]);
int k = Convert.ToInt32(tokens_n[1]);
string[] a_temp = Console.ReadLine().Split(' ');
int[] a = Array.ConvertAll(a_temp,Int32.Parse);
// use the periodicity of the shifting creating a shift between 0 and n - 1.
int shifts = k % n;
// Create a new array to hold the elements at their new positions.
int[] newPositions = new int[a.Length];
// You only need to iterate of the array once assigning each element its new position.
for(int i= 0; i < a.Length; ++i)
{
// Here is the magic: (for clarification see table below)
int position = (i - shifts + n)%n;
newPositions[position] = a[i];
}
foreach(var element in newPositions)
Console.Write($"{element} ");
}
This is more intuitive once you write it down on paper. The table might prints more values than the array contains to show the actual positions in the array.
-4 -3 -2 -1 | 0 1 2 3 4 (array indices)
=============================
2 3 4 5 | 1 2 3 4 5 (array contents without shift)
3 4 5 1 | 2 3 4 5 1 (shifted 1 time)
4 5 1 2 | 3 4 5 1 2 (shifted 2 times)
5 1 2 3 | 4 5 1 2 3 (shifted 3 times)
1 2 3 4 | 5 1 2 3 4 (shifted 4 times)
formula: i - k + n
results:
i=0: 0 - 4 + 5 = 1
i=1: 1 - 4 + 5 = 2
i=2: 2 - 4 + 5 = 3
i=3: 3 - 4 + 5 = 4
i=4: 4 - 4 + 5 = 5
i=5: 5 - 4 + 5 = 6 => 0
EDIT: I skipped the parts to check the boundaries for the sake of simplicity.
Updated answer.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution
{
static void Main(String[] args)
{
int i, j, z;
string[] tokens_n = Console.ReadLine().Split(' ');
int n = Convert.ToInt32(tokens_n[0]);
int k = Convert.ToInt32(tokens_n[1]);
string[] a_temp = Console.ReadLine().Split(' ');
int[] a = Array.ConvertAll(a_temp,Int32.Parse);
int[] temparray = new int[2*n];
//constraints
if(n >= 100000 || n < 1 )
{
System.Environment.Exit(1);
}
if(k > n || n < 1 )
{
System.Environment.Exit(1);
}
for(i = 0; i< n; i++)
{
if(a[i] > 1000000 || a[i] < 1 )
{
System.Environment.Exit(1);
}
}
for(j = 0; j<n; j++)
{
z = (j-k) %n;
if(z != 0)
{
z= (n+ z) %n;
}
temparray[z] = a[j];
}
//view array
for(i = 0; i< n; i++)
{
Console.Write(temparray[i] + " " );
}
}
}

Categories