Hacker Rank: Array left rotationImproving performance hacker rank MedianHacker Rank - Lonely...
Must a tritone substitution use a dominant seventh chord?
Has the Isbell–Freyd criterion ever been used to check that a category is concretisable?
What can I substitute for soda pop in a sweet pork recipe?
Easy code troubleshooting in wordpress
You'll find me clean when something is full
Auto Insert date into Notepad
Contradiction with Banach Fixed Point Theorem
Book where the good guy lives backwards through time and the bad guy lives forward
What is this waxed root vegetable?
Is my plan for fixing my water heater leak bad?
Linear regression when Y is bounded and discrete
How do I implement simple JS code to deploy a compiled smart contract to ganache-cli?
How can atoms be electrically neutral when there is a difference in the positions of the charges?
How to avoid being sexist when trying to employ someone to function in a very sexist environment?
How to count occurrences of Friday 13th
Exponential growth/decay formula: what happened to the other constant of integration?
Which aircraft had such a luxurious-looking navigator's station?
I can't die. Who am I?
Creature spells vs. ability to convert a permanent into a creature
How can I be pwned if I'm not registered on that site?
Closure of presentable objects under finite limits
Skis versus snow shoes - when to choose which for travelling the backcountry?
What is better: yes / no radio, or simple checkbox?
How to deny access to SQL Server to certain login over SSMS, but allow over .Net SqlClient Data Provider
Hacker Rank: Array left rotation
Improving performance hacker rank MedianHacker Rank - Lonely IntegerConverting from binary to unaryHacker Rank - Poisonous PlantsHacker rank Jesse and CookiesHackerRank Array left rotation using SwiftCircular Array Rotation C++ HackerRankTo the right, to the left, now rotateJava Left Rotate Array upto n timesHacker rank - Left rotation - PHP code feedback for Timeout
$begingroup$
This code is to solve the Hacker Rank problem array left rotation.
A left rotation operation on an array of size n shifts each of the array's elements 1 unit to the left. For example, if 2 left rotations are performed on array [1,2,3,4,5], then the array would become [3,4,5,1,2].
Given an array of n integers and a number, d, perform d left rotations on the array. Then print the updated array as a single line of space-separated integers.
public static int[] rotLeft(int[] a, int d)
{
for (int intI = 0; intI < d; intI++)
{
int temp = 0;
temp = a[0];
for (int intK = 0; intK < a.Length; intK++)
{
a[a.Length - (a.Length - intK)] = a.Length - 1 == intK ? temp : a[a.Length - (a.Length - (intK + 1))];
}
}
return a;
}
static void Main(string[] args)
{
string[] nd = Console.ReadLine().Split(' ');
int n = Convert.ToInt32(nd[0]);
int d = Convert.ToInt32(nd[1]);
int[] a = Array.ConvertAll(Console.ReadLine().Split(' '), aTemp => Convert.ToInt32(aTemp));
int[] result = rotLeft(a, d);
Console.WriteLine(string.Join(" ", result));
}
This program works fine, but it takes too long with some examples. How can I improve it?
c# algorithm programming-challenge time-limit-exceeded
New contributor
Ramakrishna is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
$endgroup$
|
show 1 more comment
$begingroup$
This code is to solve the Hacker Rank problem array left rotation.
A left rotation operation on an array of size n shifts each of the array's elements 1 unit to the left. For example, if 2 left rotations are performed on array [1,2,3,4,5], then the array would become [3,4,5,1,2].
Given an array of n integers and a number, d, perform d left rotations on the array. Then print the updated array as a single line of space-separated integers.
public static int[] rotLeft(int[] a, int d)
{
for (int intI = 0; intI < d; intI++)
{
int temp = 0;
temp = a[0];
for (int intK = 0; intK < a.Length; intK++)
{
a[a.Length - (a.Length - intK)] = a.Length - 1 == intK ? temp : a[a.Length - (a.Length - (intK + 1))];
}
}
return a;
}
static void Main(string[] args)
{
string[] nd = Console.ReadLine().Split(' ');
int n = Convert.ToInt32(nd[0]);
int d = Convert.ToInt32(nd[1]);
int[] a = Array.ConvertAll(Console.ReadLine().Split(' '), aTemp => Convert.ToInt32(aTemp));
int[] result = rotLeft(a, d);
Console.WriteLine(string.Join(" ", result));
}
This program works fine, but it takes too long with some examples. How can I improve it?
c# algorithm programming-challenge time-limit-exceeded
New contributor
Ramakrishna is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
$endgroup$
3
$begingroup$
The best code is no code at all. Do you actually need to rotate the array, or just print the elements in rotated order? Because if that’s the case then you can save a whole lot of copying around.
$endgroup$
– Konrad Rudolph
12 hours ago
$begingroup$
From O(n^2) to O(n):int n = d % a.Length; var b = a.Skip(n).Concat(a.Take(n)).ToArray();. You can always get rid of the lazy enumerable when its too slow.
$endgroup$
– Caramiriel
11 hours ago
7
$begingroup$
@Caramiriel, you've got the wrong box. The one for answers is further down the page.
$endgroup$
– Peter Taylor
10 hours ago
1
$begingroup$
@Caramiriel this isn'tO(n)becauseSkipis not clever... as far as I know it iterates the collection to skip the items.
$endgroup$
– t3chb0t
8 hours ago
2
$begingroup$
@t3chb0t Even if it goes through the array twice,2n, or200nfor that matter, is stillO(n)
$endgroup$
– TemporalWolf
6 hours ago
|
show 1 more comment
$begingroup$
This code is to solve the Hacker Rank problem array left rotation.
A left rotation operation on an array of size n shifts each of the array's elements 1 unit to the left. For example, if 2 left rotations are performed on array [1,2,3,4,5], then the array would become [3,4,5,1,2].
Given an array of n integers and a number, d, perform d left rotations on the array. Then print the updated array as a single line of space-separated integers.
public static int[] rotLeft(int[] a, int d)
{
for (int intI = 0; intI < d; intI++)
{
int temp = 0;
temp = a[0];
for (int intK = 0; intK < a.Length; intK++)
{
a[a.Length - (a.Length - intK)] = a.Length - 1 == intK ? temp : a[a.Length - (a.Length - (intK + 1))];
}
}
return a;
}
static void Main(string[] args)
{
string[] nd = Console.ReadLine().Split(' ');
int n = Convert.ToInt32(nd[0]);
int d = Convert.ToInt32(nd[1]);
int[] a = Array.ConvertAll(Console.ReadLine().Split(' '), aTemp => Convert.ToInt32(aTemp));
int[] result = rotLeft(a, d);
Console.WriteLine(string.Join(" ", result));
}
This program works fine, but it takes too long with some examples. How can I improve it?
c# algorithm programming-challenge time-limit-exceeded
New contributor
Ramakrishna is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
$endgroup$
This code is to solve the Hacker Rank problem array left rotation.
A left rotation operation on an array of size n shifts each of the array's elements 1 unit to the left. For example, if 2 left rotations are performed on array [1,2,3,4,5], then the array would become [3,4,5,1,2].
Given an array of n integers and a number, d, perform d left rotations on the array. Then print the updated array as a single line of space-separated integers.
public static int[] rotLeft(int[] a, int d)
{
for (int intI = 0; intI < d; intI++)
{
int temp = 0;
temp = a[0];
for (int intK = 0; intK < a.Length; intK++)
{
a[a.Length - (a.Length - intK)] = a.Length - 1 == intK ? temp : a[a.Length - (a.Length - (intK + 1))];
}
}
return a;
}
static void Main(string[] args)
{
string[] nd = Console.ReadLine().Split(' ');
int n = Convert.ToInt32(nd[0]);
int d = Convert.ToInt32(nd[1]);
int[] a = Array.ConvertAll(Console.ReadLine().Split(' '), aTemp => Convert.ToInt32(aTemp));
int[] result = rotLeft(a, d);
Console.WriteLine(string.Join(" ", result));
}
This program works fine, but it takes too long with some examples. How can I improve it?
c# algorithm programming-challenge time-limit-exceeded
c# algorithm programming-challenge time-limit-exceeded
New contributor
Ramakrishna is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
New contributor
Ramakrishna is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
edited 15 hours ago
Toby Speight
25.4k742116
25.4k742116
New contributor
Ramakrishna is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
asked 18 hours ago
RamakrishnaRamakrishna
485
485
New contributor
Ramakrishna is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
New contributor
Ramakrishna is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
Ramakrishna is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
3
$begingroup$
The best code is no code at all. Do you actually need to rotate the array, or just print the elements in rotated order? Because if that’s the case then you can save a whole lot of copying around.
$endgroup$
– Konrad Rudolph
12 hours ago
$begingroup$
From O(n^2) to O(n):int n = d % a.Length; var b = a.Skip(n).Concat(a.Take(n)).ToArray();. You can always get rid of the lazy enumerable when its too slow.
$endgroup$
– Caramiriel
11 hours ago
7
$begingroup$
@Caramiriel, you've got the wrong box. The one for answers is further down the page.
$endgroup$
– Peter Taylor
10 hours ago
1
$begingroup$
@Caramiriel this isn'tO(n)becauseSkipis not clever... as far as I know it iterates the collection to skip the items.
$endgroup$
– t3chb0t
8 hours ago
2
$begingroup$
@t3chb0t Even if it goes through the array twice,2n, or200nfor that matter, is stillO(n)
$endgroup$
– TemporalWolf
6 hours ago
|
show 1 more comment
3
$begingroup$
The best code is no code at all. Do you actually need to rotate the array, or just print the elements in rotated order? Because if that’s the case then you can save a whole lot of copying around.
$endgroup$
– Konrad Rudolph
12 hours ago
$begingroup$
From O(n^2) to O(n):int n = d % a.Length; var b = a.Skip(n).Concat(a.Take(n)).ToArray();. You can always get rid of the lazy enumerable when its too slow.
$endgroup$
– Caramiriel
11 hours ago
7
$begingroup$
@Caramiriel, you've got the wrong box. The one for answers is further down the page.
$endgroup$
– Peter Taylor
10 hours ago
1
$begingroup$
@Caramiriel this isn'tO(n)becauseSkipis not clever... as far as I know it iterates the collection to skip the items.
$endgroup$
– t3chb0t
8 hours ago
2
$begingroup$
@t3chb0t Even if it goes through the array twice,2n, or200nfor that matter, is stillO(n)
$endgroup$
– TemporalWolf
6 hours ago
3
3
$begingroup$
The best code is no code at all. Do you actually need to rotate the array, or just print the elements in rotated order? Because if that’s the case then you can save a whole lot of copying around.
$endgroup$
– Konrad Rudolph
12 hours ago
$begingroup$
The best code is no code at all. Do you actually need to rotate the array, or just print the elements in rotated order? Because if that’s the case then you can save a whole lot of copying around.
$endgroup$
– Konrad Rudolph
12 hours ago
$begingroup$
From O(n^2) to O(n):
int n = d % a.Length; var b = a.Skip(n).Concat(a.Take(n)).ToArray();. You can always get rid of the lazy enumerable when its too slow.$endgroup$
– Caramiriel
11 hours ago
$begingroup$
From O(n^2) to O(n):
int n = d % a.Length; var b = a.Skip(n).Concat(a.Take(n)).ToArray();. You can always get rid of the lazy enumerable when its too slow.$endgroup$
– Caramiriel
11 hours ago
7
7
$begingroup$
@Caramiriel, you've got the wrong box. The one for answers is further down the page.
$endgroup$
– Peter Taylor
10 hours ago
$begingroup$
@Caramiriel, you've got the wrong box. The one for answers is further down the page.
$endgroup$
– Peter Taylor
10 hours ago
1
1
$begingroup$
@Caramiriel this isn't
O(n) because Skip is not clever... as far as I know it iterates the collection to skip the items.$endgroup$
– t3chb0t
8 hours ago
$begingroup$
@Caramiriel this isn't
O(n) because Skip is not clever... as far as I know it iterates the collection to skip the items.$endgroup$
– t3chb0t
8 hours ago
2
2
$begingroup$
@t3chb0t Even if it goes through the array twice,
2n, or 200n for that matter, is still O(n)$endgroup$
– TemporalWolf
6 hours ago
$begingroup$
@t3chb0t Even if it goes through the array twice,
2n, or 200n for that matter, is still O(n)$endgroup$
– TemporalWolf
6 hours ago
|
show 1 more comment
5 Answers
5
active
oldest
votes
$begingroup$
About naming:
intI and intK: don't include the type in the variable name, it is obvious from the context and intellisense and as a loop index a plain i and k are more understandable.
A first simple optimization is that you can avoid the check if intK has reached the end:
a.Length - 1 == intK ?
Instead you can just iterate up to a.Length - 1 and then append temp at the end:
public static int[] rotLeft(int[] a, int d)
{
for (int intI = 0; intI < d; intI++)
{
int temp = a[0];
for (int intK = 0; intK < a.Length - 1; intK++)
{
a[a.Length - (a.Length - intK)] = a[a.Length - (a.Length - (intK + 1))];
}
a[a.Length - 1] = temp;
}
return a;
}
Next step is to consider the math:
a.Length - (a.Length - intK) = a.Length - a.Length + intK = intK
and in the same way:
a.Length - (a.Length - (intK + 1)) = intK + 1
So you could write:
public static int[] rotLeft(int[] a, int d)
{
for (int intI = 0; intI < d; intI++)
{
int temp = a[0];
for (int intK = 0; intK < a.Length - 1; intK++)
{
a[intK] = a[intK + 1];
}
a[a.Length - 1] = temp;
}
return a;
}
But the real performance problem is that you move each entry in the array d number of times. You can move each entry just once by moving it d places. A simple way to do that could be:
public static int[] rotLeft(int[] a, int d)
{
int[] temp = new int[d];
for (int i = 0; i < d; i++)
temp[i] = a[i];
for (int i = d; i < a.Length; i++)
{
a[i - d] = a[i];
}
for (int i = 0; i < d; i++)
a[a.Length - d + i] = temp[i];
return a;
}
Another issue is that you operate on the input array a directly and return it as a return value. In this way both the return value and a contains the shifted values. In a challenge like this it may not be important, but I think I would return a new array with the shifted data leaving a unchanged - in "real world":
public static int[] rotLeft(int[] a, int d)
{
int[] result = new int[a.Length];
for (int i = d; i < a.Length; i++)
{
result[i - d] = a[i];
}
for (int j = 0; j < d; j++)
{
result[a.Length - d + j] = a[j];
}
return result;
}
If you want to operate on a directly intentionally it would be more consistent returning void to signal that you're operating on the input directly.
$endgroup$
add a comment |
$begingroup$
I guess your code is slow because of the two loops and its O(n^2) complexity. You can actually solve it with only one loop by rotating the index with % (modulo). This would even allow you to rotate the array in both directions;
public static IEnumerable<T> Shift<T>(this T[] source, int count)
{
for (int i = 0; i < source.Length; i++)
{
var j =
count > 0
? (i + count) % source.Length
: (i + count + source.Length) % source.Length;
yield return source[j];
}
}
$endgroup$
7
$begingroup$
In fact, a general tip for programming challenges like this is that, whenever the challenge says "repeat this operation N times," it almost always actually means "find a faster way to get the same result as if you'd repeated the operation N times." That's because the challenges are meant to be challenging, and just writing aforloop to run the same code multiple times is really no challenge at all.
$endgroup$
– Ilmari Karonen
14 hours ago
$begingroup$
%is typically slow; andi+countcan't wrap more than once. So really you just need a conditional subtract. If you're actually copying the array, hopefully the compiler can split it into two loops that simply copy the 1st / 2nd parts of the array without doing a bunch of expensive per-index calculation, like Henrik's answer. Also hopefully the compiler will hoist thecount>0check out of the loop.
$endgroup$
– Peter Cordes
14 hours ago
7
$begingroup$
@PeterCordes - I think%is clearer and never so slow as to justify such an optimization without profiling first. I would be very surprised if it were the bottleneck in application software, rather than, say, disk IO.
$endgroup$
– Alex Reinking
14 hours ago
$begingroup$
In C, a simplistic microbenchmark doing just a modulo increment shows that it's about 6x slower on a Haswell CPU. is it better to avoid using the mod operator when possible?. Most things aren't a big deal, but integer division is slow unless it's by a compile-time constant that the compiler can turn into a multiply+shift. The OP already said that their solution for rotating an array was too slow rotating 1 element at a time, so presumably a factor of 6 (or more if the compiler can turn it into 2x memcpy) could matter.
$endgroup$
– Peter Cordes
2 hours ago
$begingroup$
You can hoist thecount > 0check out of the loop by calculating the left-rotate count once.if(count < 0) count += source.Length;Then the loop becomes much more readable, and probably more efficient unless the compiler already managed to do that for you.
$endgroup$
– Peter Cordes
2 hours ago
add a comment |
$begingroup$
static void Main(string[] args)
{
string[] nd = Console.ReadLine().Split(' ');
int n = Convert.ToInt32(nd[0]);
int d = Convert.ToInt32(nd[1]);
int[] a = Array.ConvertAll(Console.ReadLine().Split(' '), aTemp => Convert.ToInt32(aTemp));
Don't Repeat Yourself. There's an easy opportunity here to factor out a method which reads an array of integers from stdin.
In general I would prefer to remove the explicit lambda, but I think that in this case just passing Convert.ToInt32 would be ambiguous because of the overloads.
int[] result = rotLeft(a, d);
Console.WriteLine(string.Join(" ", result));
}
When implementing a spec, ask yourself what the inputs and the outputs are. As long as you respect those, you should be at liberty to optimise the processing. So it's not actually necessary to rotate the array: just to print the result of rotating it.
Console.Write(a[d]);
for (int i = d+1; i < a.Length; i++)
{
Console.Write(' ');
Console.Write(a[i]);
}
for (int i = 0; i < d; i++)
{
Console.Write(' ');
Console.Write(a[i]);
}
But I think that that code probably has a bug. Does the spec make any guarantees about the value of d other than that it's an integer? Can it be negative? Can it be greater than n?
$endgroup$
$begingroup$
Most of the I/O code is provided as part of the challenge. The only thing OP has to provide is the code inside the rotLeft function, which should return the rotated array.
$endgroup$
– jcaron
12 hours ago
$begingroup$
@jcaron, it's OP's responsibility to ask only about their own code. The help centre is quite explicit that any aspect of the code posted is fair game for feedback and criticism.
$endgroup$
– Peter Taylor
11 hours ago
add a comment |
$begingroup$
- "mirror" the first d elements
- mirror the whole array
- mirror the size-d first elements.
In place. Linear time complexity. 0(1) extra room needed.
$endgroup$
add a comment |
$begingroup$
You are focusing on the wrong portion of the problem. You're thinking the array needs to be rotated. The output of the array needs to be "rotated" but the array can remain as-is.
So simply write a loop that starts at the middle of the array, incrementing until it hits the end, and then continues along from the beginning until it hits the index just before the one you started at.
The output of that loop is the "rotated" array, from the visibility of the testing framework.
string sep = "";
for (int i = d; i < a.Length; i++) {
Console.Write(sep);
Console.Write(a[i]);
sep = " ";
}
for (int i = 0; i < d; i++)
{
Console.Write(sep);
Console.Write(a[i]);
sep = " ";
}
This is a great reason why you should sometimes see hackerrank as a poor place to really learn programming.
hackerrank primarily contains programming problems harvested from programming competitions. Competitions where these problems are meant to be solved fast, with a time deadline. This means that the problems are more about building a quick, clever, solution and less about really learning the lessons that would help you in a programming career.
Another example of a solution is
string sep = "";
for (int i = d; a.Length + d - i > 0; i++) {
Console.Write(sep);
Console.Write(a[i % a.Length]);
sep = " ";
}
Which is, according to hackerranks estimation, "just as good" as the above solution, but is far less readable.
$endgroup$
$begingroup$
Well one thing one should certainly learn from this challenge is whatstring.Joindoes and how it avoids the rather awful for loop :) (The given solution also misses some necessary modulo ops)
$endgroup$
– Voo
5 hours ago
$begingroup$
@Voo Out of curiosity, which modulo does this miss? I know I wrote it by hand without the aid of a computer, but the loop (in my 5 element example, starting at index 3 would be 3, 4, 5, 6, 7 (8 would be 5 + 3 - 8, so it wouldn't get there). and 3 % 5 = 3, 4 % 5 = 4, 5 % 5 = 0, 6 % 5 = 1, 7 % 5 = 2. Now, I just might have a bug in there after all; but, maybe not, which is a perfect example of why writing it this way is less than ideal and whyhackerranks fascination with programming competitions as question banks is bad.
$endgroup$
– Edwin Buck
4 hours ago
1
$begingroup$
You're supposed to do n rotations. Nowhere does it say that n < arr.Length. You could have an array of1,2,3and d=5. Both of your solutions fail with an out of bounds there.
$endgroup$
– Voo
3 hours ago
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
return StackExchange.using("mathjaxEditing", function () {
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
});
});
}, "mathjax-editing");
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "196"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Ramakrishna is a new contributor. Be nice, and check out our Code of Conduct.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f214680%2fhacker-rank-array-left-rotation%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
5 Answers
5
active
oldest
votes
5 Answers
5
active
oldest
votes
active
oldest
votes
active
oldest
votes
$begingroup$
About naming:
intI and intK: don't include the type in the variable name, it is obvious from the context and intellisense and as a loop index a plain i and k are more understandable.
A first simple optimization is that you can avoid the check if intK has reached the end:
a.Length - 1 == intK ?
Instead you can just iterate up to a.Length - 1 and then append temp at the end:
public static int[] rotLeft(int[] a, int d)
{
for (int intI = 0; intI < d; intI++)
{
int temp = a[0];
for (int intK = 0; intK < a.Length - 1; intK++)
{
a[a.Length - (a.Length - intK)] = a[a.Length - (a.Length - (intK + 1))];
}
a[a.Length - 1] = temp;
}
return a;
}
Next step is to consider the math:
a.Length - (a.Length - intK) = a.Length - a.Length + intK = intK
and in the same way:
a.Length - (a.Length - (intK + 1)) = intK + 1
So you could write:
public static int[] rotLeft(int[] a, int d)
{
for (int intI = 0; intI < d; intI++)
{
int temp = a[0];
for (int intK = 0; intK < a.Length - 1; intK++)
{
a[intK] = a[intK + 1];
}
a[a.Length - 1] = temp;
}
return a;
}
But the real performance problem is that you move each entry in the array d number of times. You can move each entry just once by moving it d places. A simple way to do that could be:
public static int[] rotLeft(int[] a, int d)
{
int[] temp = new int[d];
for (int i = 0; i < d; i++)
temp[i] = a[i];
for (int i = d; i < a.Length; i++)
{
a[i - d] = a[i];
}
for (int i = 0; i < d; i++)
a[a.Length - d + i] = temp[i];
return a;
}
Another issue is that you operate on the input array a directly and return it as a return value. In this way both the return value and a contains the shifted values. In a challenge like this it may not be important, but I think I would return a new array with the shifted data leaving a unchanged - in "real world":
public static int[] rotLeft(int[] a, int d)
{
int[] result = new int[a.Length];
for (int i = d; i < a.Length; i++)
{
result[i - d] = a[i];
}
for (int j = 0; j < d; j++)
{
result[a.Length - d + j] = a[j];
}
return result;
}
If you want to operate on a directly intentionally it would be more consistent returning void to signal that you're operating on the input directly.
$endgroup$
add a comment |
$begingroup$
About naming:
intI and intK: don't include the type in the variable name, it is obvious from the context and intellisense and as a loop index a plain i and k are more understandable.
A first simple optimization is that you can avoid the check if intK has reached the end:
a.Length - 1 == intK ?
Instead you can just iterate up to a.Length - 1 and then append temp at the end:
public static int[] rotLeft(int[] a, int d)
{
for (int intI = 0; intI < d; intI++)
{
int temp = a[0];
for (int intK = 0; intK < a.Length - 1; intK++)
{
a[a.Length - (a.Length - intK)] = a[a.Length - (a.Length - (intK + 1))];
}
a[a.Length - 1] = temp;
}
return a;
}
Next step is to consider the math:
a.Length - (a.Length - intK) = a.Length - a.Length + intK = intK
and in the same way:
a.Length - (a.Length - (intK + 1)) = intK + 1
So you could write:
public static int[] rotLeft(int[] a, int d)
{
for (int intI = 0; intI < d; intI++)
{
int temp = a[0];
for (int intK = 0; intK < a.Length - 1; intK++)
{
a[intK] = a[intK + 1];
}
a[a.Length - 1] = temp;
}
return a;
}
But the real performance problem is that you move each entry in the array d number of times. You can move each entry just once by moving it d places. A simple way to do that could be:
public static int[] rotLeft(int[] a, int d)
{
int[] temp = new int[d];
for (int i = 0; i < d; i++)
temp[i] = a[i];
for (int i = d; i < a.Length; i++)
{
a[i - d] = a[i];
}
for (int i = 0; i < d; i++)
a[a.Length - d + i] = temp[i];
return a;
}
Another issue is that you operate on the input array a directly and return it as a return value. In this way both the return value and a contains the shifted values. In a challenge like this it may not be important, but I think I would return a new array with the shifted data leaving a unchanged - in "real world":
public static int[] rotLeft(int[] a, int d)
{
int[] result = new int[a.Length];
for (int i = d; i < a.Length; i++)
{
result[i - d] = a[i];
}
for (int j = 0; j < d; j++)
{
result[a.Length - d + j] = a[j];
}
return result;
}
If you want to operate on a directly intentionally it would be more consistent returning void to signal that you're operating on the input directly.
$endgroup$
add a comment |
$begingroup$
About naming:
intI and intK: don't include the type in the variable name, it is obvious from the context and intellisense and as a loop index a plain i and k are more understandable.
A first simple optimization is that you can avoid the check if intK has reached the end:
a.Length - 1 == intK ?
Instead you can just iterate up to a.Length - 1 and then append temp at the end:
public static int[] rotLeft(int[] a, int d)
{
for (int intI = 0; intI < d; intI++)
{
int temp = a[0];
for (int intK = 0; intK < a.Length - 1; intK++)
{
a[a.Length - (a.Length - intK)] = a[a.Length - (a.Length - (intK + 1))];
}
a[a.Length - 1] = temp;
}
return a;
}
Next step is to consider the math:
a.Length - (a.Length - intK) = a.Length - a.Length + intK = intK
and in the same way:
a.Length - (a.Length - (intK + 1)) = intK + 1
So you could write:
public static int[] rotLeft(int[] a, int d)
{
for (int intI = 0; intI < d; intI++)
{
int temp = a[0];
for (int intK = 0; intK < a.Length - 1; intK++)
{
a[intK] = a[intK + 1];
}
a[a.Length - 1] = temp;
}
return a;
}
But the real performance problem is that you move each entry in the array d number of times. You can move each entry just once by moving it d places. A simple way to do that could be:
public static int[] rotLeft(int[] a, int d)
{
int[] temp = new int[d];
for (int i = 0; i < d; i++)
temp[i] = a[i];
for (int i = d; i < a.Length; i++)
{
a[i - d] = a[i];
}
for (int i = 0; i < d; i++)
a[a.Length - d + i] = temp[i];
return a;
}
Another issue is that you operate on the input array a directly and return it as a return value. In this way both the return value and a contains the shifted values. In a challenge like this it may not be important, but I think I would return a new array with the shifted data leaving a unchanged - in "real world":
public static int[] rotLeft(int[] a, int d)
{
int[] result = new int[a.Length];
for (int i = d; i < a.Length; i++)
{
result[i - d] = a[i];
}
for (int j = 0; j < d; j++)
{
result[a.Length - d + j] = a[j];
}
return result;
}
If you want to operate on a directly intentionally it would be more consistent returning void to signal that you're operating on the input directly.
$endgroup$
About naming:
intI and intK: don't include the type in the variable name, it is obvious from the context and intellisense and as a loop index a plain i and k are more understandable.
A first simple optimization is that you can avoid the check if intK has reached the end:
a.Length - 1 == intK ?
Instead you can just iterate up to a.Length - 1 and then append temp at the end:
public static int[] rotLeft(int[] a, int d)
{
for (int intI = 0; intI < d; intI++)
{
int temp = a[0];
for (int intK = 0; intK < a.Length - 1; intK++)
{
a[a.Length - (a.Length - intK)] = a[a.Length - (a.Length - (intK + 1))];
}
a[a.Length - 1] = temp;
}
return a;
}
Next step is to consider the math:
a.Length - (a.Length - intK) = a.Length - a.Length + intK = intK
and in the same way:
a.Length - (a.Length - (intK + 1)) = intK + 1
So you could write:
public static int[] rotLeft(int[] a, int d)
{
for (int intI = 0; intI < d; intI++)
{
int temp = a[0];
for (int intK = 0; intK < a.Length - 1; intK++)
{
a[intK] = a[intK + 1];
}
a[a.Length - 1] = temp;
}
return a;
}
But the real performance problem is that you move each entry in the array d number of times. You can move each entry just once by moving it d places. A simple way to do that could be:
public static int[] rotLeft(int[] a, int d)
{
int[] temp = new int[d];
for (int i = 0; i < d; i++)
temp[i] = a[i];
for (int i = d; i < a.Length; i++)
{
a[i - d] = a[i];
}
for (int i = 0; i < d; i++)
a[a.Length - d + i] = temp[i];
return a;
}
Another issue is that you operate on the input array a directly and return it as a return value. In this way both the return value and a contains the shifted values. In a challenge like this it may not be important, but I think I would return a new array with the shifted data leaving a unchanged - in "real world":
public static int[] rotLeft(int[] a, int d)
{
int[] result = new int[a.Length];
for (int i = d; i < a.Length; i++)
{
result[i - d] = a[i];
}
for (int j = 0; j < d; j++)
{
result[a.Length - d + j] = a[j];
}
return result;
}
If you want to operate on a directly intentionally it would be more consistent returning void to signal that you're operating on the input directly.
edited 16 hours ago
answered 16 hours ago
Henrik HansenHenrik Hansen
7,63011229
7,63011229
add a comment |
add a comment |
$begingroup$
I guess your code is slow because of the two loops and its O(n^2) complexity. You can actually solve it with only one loop by rotating the index with % (modulo). This would even allow you to rotate the array in both directions;
public static IEnumerable<T> Shift<T>(this T[] source, int count)
{
for (int i = 0; i < source.Length; i++)
{
var j =
count > 0
? (i + count) % source.Length
: (i + count + source.Length) % source.Length;
yield return source[j];
}
}
$endgroup$
7
$begingroup$
In fact, a general tip for programming challenges like this is that, whenever the challenge says "repeat this operation N times," it almost always actually means "find a faster way to get the same result as if you'd repeated the operation N times." That's because the challenges are meant to be challenging, and just writing aforloop to run the same code multiple times is really no challenge at all.
$endgroup$
– Ilmari Karonen
14 hours ago
$begingroup$
%is typically slow; andi+countcan't wrap more than once. So really you just need a conditional subtract. If you're actually copying the array, hopefully the compiler can split it into two loops that simply copy the 1st / 2nd parts of the array without doing a bunch of expensive per-index calculation, like Henrik's answer. Also hopefully the compiler will hoist thecount>0check out of the loop.
$endgroup$
– Peter Cordes
14 hours ago
7
$begingroup$
@PeterCordes - I think%is clearer and never so slow as to justify such an optimization without profiling first. I would be very surprised if it were the bottleneck in application software, rather than, say, disk IO.
$endgroup$
– Alex Reinking
14 hours ago
$begingroup$
In C, a simplistic microbenchmark doing just a modulo increment shows that it's about 6x slower on a Haswell CPU. is it better to avoid using the mod operator when possible?. Most things aren't a big deal, but integer division is slow unless it's by a compile-time constant that the compiler can turn into a multiply+shift. The OP already said that their solution for rotating an array was too slow rotating 1 element at a time, so presumably a factor of 6 (or more if the compiler can turn it into 2x memcpy) could matter.
$endgroup$
– Peter Cordes
2 hours ago
$begingroup$
You can hoist thecount > 0check out of the loop by calculating the left-rotate count once.if(count < 0) count += source.Length;Then the loop becomes much more readable, and probably more efficient unless the compiler already managed to do that for you.
$endgroup$
– Peter Cordes
2 hours ago
add a comment |
$begingroup$
I guess your code is slow because of the two loops and its O(n^2) complexity. You can actually solve it with only one loop by rotating the index with % (modulo). This would even allow you to rotate the array in both directions;
public static IEnumerable<T> Shift<T>(this T[] source, int count)
{
for (int i = 0; i < source.Length; i++)
{
var j =
count > 0
? (i + count) % source.Length
: (i + count + source.Length) % source.Length;
yield return source[j];
}
}
$endgroup$
7
$begingroup$
In fact, a general tip for programming challenges like this is that, whenever the challenge says "repeat this operation N times," it almost always actually means "find a faster way to get the same result as if you'd repeated the operation N times." That's because the challenges are meant to be challenging, and just writing aforloop to run the same code multiple times is really no challenge at all.
$endgroup$
– Ilmari Karonen
14 hours ago
$begingroup$
%is typically slow; andi+countcan't wrap more than once. So really you just need a conditional subtract. If you're actually copying the array, hopefully the compiler can split it into two loops that simply copy the 1st / 2nd parts of the array without doing a bunch of expensive per-index calculation, like Henrik's answer. Also hopefully the compiler will hoist thecount>0check out of the loop.
$endgroup$
– Peter Cordes
14 hours ago
7
$begingroup$
@PeterCordes - I think%is clearer and never so slow as to justify such an optimization without profiling first. I would be very surprised if it were the bottleneck in application software, rather than, say, disk IO.
$endgroup$
– Alex Reinking
14 hours ago
$begingroup$
In C, a simplistic microbenchmark doing just a modulo increment shows that it's about 6x slower on a Haswell CPU. is it better to avoid using the mod operator when possible?. Most things aren't a big deal, but integer division is slow unless it's by a compile-time constant that the compiler can turn into a multiply+shift. The OP already said that their solution for rotating an array was too slow rotating 1 element at a time, so presumably a factor of 6 (or more if the compiler can turn it into 2x memcpy) could matter.
$endgroup$
– Peter Cordes
2 hours ago
$begingroup$
You can hoist thecount > 0check out of the loop by calculating the left-rotate count once.if(count < 0) count += source.Length;Then the loop becomes much more readable, and probably more efficient unless the compiler already managed to do that for you.
$endgroup$
– Peter Cordes
2 hours ago
add a comment |
$begingroup$
I guess your code is slow because of the two loops and its O(n^2) complexity. You can actually solve it with only one loop by rotating the index with % (modulo). This would even allow you to rotate the array in both directions;
public static IEnumerable<T> Shift<T>(this T[] source, int count)
{
for (int i = 0; i < source.Length; i++)
{
var j =
count > 0
? (i + count) % source.Length
: (i + count + source.Length) % source.Length;
yield return source[j];
}
}
$endgroup$
I guess your code is slow because of the two loops and its O(n^2) complexity. You can actually solve it with only one loop by rotating the index with % (modulo). This would even allow you to rotate the array in both directions;
public static IEnumerable<T> Shift<T>(this T[] source, int count)
{
for (int i = 0; i < source.Length; i++)
{
var j =
count > 0
? (i + count) % source.Length
: (i + count + source.Length) % source.Length;
yield return source[j];
}
}
answered 16 hours ago
t3chb0tt3chb0t
34.9k751122
34.9k751122
7
$begingroup$
In fact, a general tip for programming challenges like this is that, whenever the challenge says "repeat this operation N times," it almost always actually means "find a faster way to get the same result as if you'd repeated the operation N times." That's because the challenges are meant to be challenging, and just writing aforloop to run the same code multiple times is really no challenge at all.
$endgroup$
– Ilmari Karonen
14 hours ago
$begingroup$
%is typically slow; andi+countcan't wrap more than once. So really you just need a conditional subtract. If you're actually copying the array, hopefully the compiler can split it into two loops that simply copy the 1st / 2nd parts of the array without doing a bunch of expensive per-index calculation, like Henrik's answer. Also hopefully the compiler will hoist thecount>0check out of the loop.
$endgroup$
– Peter Cordes
14 hours ago
7
$begingroup$
@PeterCordes - I think%is clearer and never so slow as to justify such an optimization without profiling first. I would be very surprised if it were the bottleneck in application software, rather than, say, disk IO.
$endgroup$
– Alex Reinking
14 hours ago
$begingroup$
In C, a simplistic microbenchmark doing just a modulo increment shows that it's about 6x slower on a Haswell CPU. is it better to avoid using the mod operator when possible?. Most things aren't a big deal, but integer division is slow unless it's by a compile-time constant that the compiler can turn into a multiply+shift. The OP already said that their solution for rotating an array was too slow rotating 1 element at a time, so presumably a factor of 6 (or more if the compiler can turn it into 2x memcpy) could matter.
$endgroup$
– Peter Cordes
2 hours ago
$begingroup$
You can hoist thecount > 0check out of the loop by calculating the left-rotate count once.if(count < 0) count += source.Length;Then the loop becomes much more readable, and probably more efficient unless the compiler already managed to do that for you.
$endgroup$
– Peter Cordes
2 hours ago
add a comment |
7
$begingroup$
In fact, a general tip for programming challenges like this is that, whenever the challenge says "repeat this operation N times," it almost always actually means "find a faster way to get the same result as if you'd repeated the operation N times." That's because the challenges are meant to be challenging, and just writing aforloop to run the same code multiple times is really no challenge at all.
$endgroup$
– Ilmari Karonen
14 hours ago
$begingroup$
%is typically slow; andi+countcan't wrap more than once. So really you just need a conditional subtract. If you're actually copying the array, hopefully the compiler can split it into two loops that simply copy the 1st / 2nd parts of the array without doing a bunch of expensive per-index calculation, like Henrik's answer. Also hopefully the compiler will hoist thecount>0check out of the loop.
$endgroup$
– Peter Cordes
14 hours ago
7
$begingroup$
@PeterCordes - I think%is clearer and never so slow as to justify such an optimization without profiling first. I would be very surprised if it were the bottleneck in application software, rather than, say, disk IO.
$endgroup$
– Alex Reinking
14 hours ago
$begingroup$
In C, a simplistic microbenchmark doing just a modulo increment shows that it's about 6x slower on a Haswell CPU. is it better to avoid using the mod operator when possible?. Most things aren't a big deal, but integer division is slow unless it's by a compile-time constant that the compiler can turn into a multiply+shift. The OP already said that their solution for rotating an array was too slow rotating 1 element at a time, so presumably a factor of 6 (or more if the compiler can turn it into 2x memcpy) could matter.
$endgroup$
– Peter Cordes
2 hours ago
$begingroup$
You can hoist thecount > 0check out of the loop by calculating the left-rotate count once.if(count < 0) count += source.Length;Then the loop becomes much more readable, and probably more efficient unless the compiler already managed to do that for you.
$endgroup$
– Peter Cordes
2 hours ago
7
7
$begingroup$
In fact, a general tip for programming challenges like this is that, whenever the challenge says "repeat this operation N times," it almost always actually means "find a faster way to get the same result as if you'd repeated the operation N times." That's because the challenges are meant to be challenging, and just writing a
for loop to run the same code multiple times is really no challenge at all.$endgroup$
– Ilmari Karonen
14 hours ago
$begingroup$
In fact, a general tip for programming challenges like this is that, whenever the challenge says "repeat this operation N times," it almost always actually means "find a faster way to get the same result as if you'd repeated the operation N times." That's because the challenges are meant to be challenging, and just writing a
for loop to run the same code multiple times is really no challenge at all.$endgroup$
– Ilmari Karonen
14 hours ago
$begingroup$
% is typically slow; and i+count can't wrap more than once. So really you just need a conditional subtract. If you're actually copying the array, hopefully the compiler can split it into two loops that simply copy the 1st / 2nd parts of the array without doing a bunch of expensive per-index calculation, like Henrik's answer. Also hopefully the compiler will hoist the count>0 check out of the loop.$endgroup$
– Peter Cordes
14 hours ago
$begingroup$
% is typically slow; and i+count can't wrap more than once. So really you just need a conditional subtract. If you're actually copying the array, hopefully the compiler can split it into two loops that simply copy the 1st / 2nd parts of the array without doing a bunch of expensive per-index calculation, like Henrik's answer. Also hopefully the compiler will hoist the count>0 check out of the loop.$endgroup$
– Peter Cordes
14 hours ago
7
7
$begingroup$
@PeterCordes - I think
% is clearer and never so slow as to justify such an optimization without profiling first. I would be very surprised if it were the bottleneck in application software, rather than, say, disk IO.$endgroup$
– Alex Reinking
14 hours ago
$begingroup$
@PeterCordes - I think
% is clearer and never so slow as to justify such an optimization without profiling first. I would be very surprised if it were the bottleneck in application software, rather than, say, disk IO.$endgroup$
– Alex Reinking
14 hours ago
$begingroup$
In C, a simplistic microbenchmark doing just a modulo increment shows that it's about 6x slower on a Haswell CPU. is it better to avoid using the mod operator when possible?. Most things aren't a big deal, but integer division is slow unless it's by a compile-time constant that the compiler can turn into a multiply+shift. The OP already said that their solution for rotating an array was too slow rotating 1 element at a time, so presumably a factor of 6 (or more if the compiler can turn it into 2x memcpy) could matter.
$endgroup$
– Peter Cordes
2 hours ago
$begingroup$
In C, a simplistic microbenchmark doing just a modulo increment shows that it's about 6x slower on a Haswell CPU. is it better to avoid using the mod operator when possible?. Most things aren't a big deal, but integer division is slow unless it's by a compile-time constant that the compiler can turn into a multiply+shift. The OP already said that their solution for rotating an array was too slow rotating 1 element at a time, so presumably a factor of 6 (or more if the compiler can turn it into 2x memcpy) could matter.
$endgroup$
– Peter Cordes
2 hours ago
$begingroup$
You can hoist the
count > 0 check out of the loop by calculating the left-rotate count once. if(count < 0) count += source.Length; Then the loop becomes much more readable, and probably more efficient unless the compiler already managed to do that for you.$endgroup$
– Peter Cordes
2 hours ago
$begingroup$
You can hoist the
count > 0 check out of the loop by calculating the left-rotate count once. if(count < 0) count += source.Length; Then the loop becomes much more readable, and probably more efficient unless the compiler already managed to do that for you.$endgroup$
– Peter Cordes
2 hours ago
add a comment |
$begingroup$
static void Main(string[] args)
{
string[] nd = Console.ReadLine().Split(' ');
int n = Convert.ToInt32(nd[0]);
int d = Convert.ToInt32(nd[1]);
int[] a = Array.ConvertAll(Console.ReadLine().Split(' '), aTemp => Convert.ToInt32(aTemp));
Don't Repeat Yourself. There's an easy opportunity here to factor out a method which reads an array of integers from stdin.
In general I would prefer to remove the explicit lambda, but I think that in this case just passing Convert.ToInt32 would be ambiguous because of the overloads.
int[] result = rotLeft(a, d);
Console.WriteLine(string.Join(" ", result));
}
When implementing a spec, ask yourself what the inputs and the outputs are. As long as you respect those, you should be at liberty to optimise the processing. So it's not actually necessary to rotate the array: just to print the result of rotating it.
Console.Write(a[d]);
for (int i = d+1; i < a.Length; i++)
{
Console.Write(' ');
Console.Write(a[i]);
}
for (int i = 0; i < d; i++)
{
Console.Write(' ');
Console.Write(a[i]);
}
But I think that that code probably has a bug. Does the spec make any guarantees about the value of d other than that it's an integer? Can it be negative? Can it be greater than n?
$endgroup$
$begingroup$
Most of the I/O code is provided as part of the challenge. The only thing OP has to provide is the code inside the rotLeft function, which should return the rotated array.
$endgroup$
– jcaron
12 hours ago
$begingroup$
@jcaron, it's OP's responsibility to ask only about their own code. The help centre is quite explicit that any aspect of the code posted is fair game for feedback and criticism.
$endgroup$
– Peter Taylor
11 hours ago
add a comment |
$begingroup$
static void Main(string[] args)
{
string[] nd = Console.ReadLine().Split(' ');
int n = Convert.ToInt32(nd[0]);
int d = Convert.ToInt32(nd[1]);
int[] a = Array.ConvertAll(Console.ReadLine().Split(' '), aTemp => Convert.ToInt32(aTemp));
Don't Repeat Yourself. There's an easy opportunity here to factor out a method which reads an array of integers from stdin.
In general I would prefer to remove the explicit lambda, but I think that in this case just passing Convert.ToInt32 would be ambiguous because of the overloads.
int[] result = rotLeft(a, d);
Console.WriteLine(string.Join(" ", result));
}
When implementing a spec, ask yourself what the inputs and the outputs are. As long as you respect those, you should be at liberty to optimise the processing. So it's not actually necessary to rotate the array: just to print the result of rotating it.
Console.Write(a[d]);
for (int i = d+1; i < a.Length; i++)
{
Console.Write(' ');
Console.Write(a[i]);
}
for (int i = 0; i < d; i++)
{
Console.Write(' ');
Console.Write(a[i]);
}
But I think that that code probably has a bug. Does the spec make any guarantees about the value of d other than that it's an integer? Can it be negative? Can it be greater than n?
$endgroup$
$begingroup$
Most of the I/O code is provided as part of the challenge. The only thing OP has to provide is the code inside the rotLeft function, which should return the rotated array.
$endgroup$
– jcaron
12 hours ago
$begingroup$
@jcaron, it's OP's responsibility to ask only about their own code. The help centre is quite explicit that any aspect of the code posted is fair game for feedback and criticism.
$endgroup$
– Peter Taylor
11 hours ago
add a comment |
$begingroup$
static void Main(string[] args)
{
string[] nd = Console.ReadLine().Split(' ');
int n = Convert.ToInt32(nd[0]);
int d = Convert.ToInt32(nd[1]);
int[] a = Array.ConvertAll(Console.ReadLine().Split(' '), aTemp => Convert.ToInt32(aTemp));
Don't Repeat Yourself. There's an easy opportunity here to factor out a method which reads an array of integers from stdin.
In general I would prefer to remove the explicit lambda, but I think that in this case just passing Convert.ToInt32 would be ambiguous because of the overloads.
int[] result = rotLeft(a, d);
Console.WriteLine(string.Join(" ", result));
}
When implementing a spec, ask yourself what the inputs and the outputs are. As long as you respect those, you should be at liberty to optimise the processing. So it's not actually necessary to rotate the array: just to print the result of rotating it.
Console.Write(a[d]);
for (int i = d+1; i < a.Length; i++)
{
Console.Write(' ');
Console.Write(a[i]);
}
for (int i = 0; i < d; i++)
{
Console.Write(' ');
Console.Write(a[i]);
}
But I think that that code probably has a bug. Does the spec make any guarantees about the value of d other than that it's an integer? Can it be negative? Can it be greater than n?
$endgroup$
static void Main(string[] args)
{
string[] nd = Console.ReadLine().Split(' ');
int n = Convert.ToInt32(nd[0]);
int d = Convert.ToInt32(nd[1]);
int[] a = Array.ConvertAll(Console.ReadLine().Split(' '), aTemp => Convert.ToInt32(aTemp));
Don't Repeat Yourself. There's an easy opportunity here to factor out a method which reads an array of integers from stdin.
In general I would prefer to remove the explicit lambda, but I think that in this case just passing Convert.ToInt32 would be ambiguous because of the overloads.
int[] result = rotLeft(a, d);
Console.WriteLine(string.Join(" ", result));
}
When implementing a spec, ask yourself what the inputs and the outputs are. As long as you respect those, you should be at liberty to optimise the processing. So it's not actually necessary to rotate the array: just to print the result of rotating it.
Console.Write(a[d]);
for (int i = d+1; i < a.Length; i++)
{
Console.Write(' ');
Console.Write(a[i]);
}
for (int i = 0; i < d; i++)
{
Console.Write(' ');
Console.Write(a[i]);
}
But I think that that code probably has a bug. Does the spec make any guarantees about the value of d other than that it's an integer? Can it be negative? Can it be greater than n?
answered 16 hours ago
Peter TaylorPeter Taylor
17.5k2862
17.5k2862
$begingroup$
Most of the I/O code is provided as part of the challenge. The only thing OP has to provide is the code inside the rotLeft function, which should return the rotated array.
$endgroup$
– jcaron
12 hours ago
$begingroup$
@jcaron, it's OP's responsibility to ask only about their own code. The help centre is quite explicit that any aspect of the code posted is fair game for feedback and criticism.
$endgroup$
– Peter Taylor
11 hours ago
add a comment |
$begingroup$
Most of the I/O code is provided as part of the challenge. The only thing OP has to provide is the code inside the rotLeft function, which should return the rotated array.
$endgroup$
– jcaron
12 hours ago
$begingroup$
@jcaron, it's OP's responsibility to ask only about their own code. The help centre is quite explicit that any aspect of the code posted is fair game for feedback and criticism.
$endgroup$
– Peter Taylor
11 hours ago
$begingroup$
Most of the I/O code is provided as part of the challenge. The only thing OP has to provide is the code inside the rotLeft function, which should return the rotated array.
$endgroup$
– jcaron
12 hours ago
$begingroup$
Most of the I/O code is provided as part of the challenge. The only thing OP has to provide is the code inside the rotLeft function, which should return the rotated array.
$endgroup$
– jcaron
12 hours ago
$begingroup$
@jcaron, it's OP's responsibility to ask only about their own code. The help centre is quite explicit that any aspect of the code posted is fair game for feedback and criticism.
$endgroup$
– Peter Taylor
11 hours ago
$begingroup$
@jcaron, it's OP's responsibility to ask only about their own code. The help centre is quite explicit that any aspect of the code posted is fair game for feedback and criticism.
$endgroup$
– Peter Taylor
11 hours ago
add a comment |
$begingroup$
- "mirror" the first d elements
- mirror the whole array
- mirror the size-d first elements.
In place. Linear time complexity. 0(1) extra room needed.
$endgroup$
add a comment |
$begingroup$
- "mirror" the first d elements
- mirror the whole array
- mirror the size-d first elements.
In place. Linear time complexity. 0(1) extra room needed.
$endgroup$
add a comment |
$begingroup$
- "mirror" the first d elements
- mirror the whole array
- mirror the size-d first elements.
In place. Linear time complexity. 0(1) extra room needed.
$endgroup$
- "mirror" the first d elements
- mirror the whole array
- mirror the size-d first elements.
In place. Linear time complexity. 0(1) extra room needed.
answered 15 hours ago
Michel BillaudMichel Billaud
1734
1734
add a comment |
add a comment |
$begingroup$
You are focusing on the wrong portion of the problem. You're thinking the array needs to be rotated. The output of the array needs to be "rotated" but the array can remain as-is.
So simply write a loop that starts at the middle of the array, incrementing until it hits the end, and then continues along from the beginning until it hits the index just before the one you started at.
The output of that loop is the "rotated" array, from the visibility of the testing framework.
string sep = "";
for (int i = d; i < a.Length; i++) {
Console.Write(sep);
Console.Write(a[i]);
sep = " ";
}
for (int i = 0; i < d; i++)
{
Console.Write(sep);
Console.Write(a[i]);
sep = " ";
}
This is a great reason why you should sometimes see hackerrank as a poor place to really learn programming.
hackerrank primarily contains programming problems harvested from programming competitions. Competitions where these problems are meant to be solved fast, with a time deadline. This means that the problems are more about building a quick, clever, solution and less about really learning the lessons that would help you in a programming career.
Another example of a solution is
string sep = "";
for (int i = d; a.Length + d - i > 0; i++) {
Console.Write(sep);
Console.Write(a[i % a.Length]);
sep = " ";
}
Which is, according to hackerranks estimation, "just as good" as the above solution, but is far less readable.
$endgroup$
$begingroup$
Well one thing one should certainly learn from this challenge is whatstring.Joindoes and how it avoids the rather awful for loop :) (The given solution also misses some necessary modulo ops)
$endgroup$
– Voo
5 hours ago
$begingroup$
@Voo Out of curiosity, which modulo does this miss? I know I wrote it by hand without the aid of a computer, but the loop (in my 5 element example, starting at index 3 would be 3, 4, 5, 6, 7 (8 would be 5 + 3 - 8, so it wouldn't get there). and 3 % 5 = 3, 4 % 5 = 4, 5 % 5 = 0, 6 % 5 = 1, 7 % 5 = 2. Now, I just might have a bug in there after all; but, maybe not, which is a perfect example of why writing it this way is less than ideal and whyhackerranks fascination with programming competitions as question banks is bad.
$endgroup$
– Edwin Buck
4 hours ago
1
$begingroup$
You're supposed to do n rotations. Nowhere does it say that n < arr.Length. You could have an array of1,2,3and d=5. Both of your solutions fail with an out of bounds there.
$endgroup$
– Voo
3 hours ago
add a comment |
$begingroup$
You are focusing on the wrong portion of the problem. You're thinking the array needs to be rotated. The output of the array needs to be "rotated" but the array can remain as-is.
So simply write a loop that starts at the middle of the array, incrementing until it hits the end, and then continues along from the beginning until it hits the index just before the one you started at.
The output of that loop is the "rotated" array, from the visibility of the testing framework.
string sep = "";
for (int i = d; i < a.Length; i++) {
Console.Write(sep);
Console.Write(a[i]);
sep = " ";
}
for (int i = 0; i < d; i++)
{
Console.Write(sep);
Console.Write(a[i]);
sep = " ";
}
This is a great reason why you should sometimes see hackerrank as a poor place to really learn programming.
hackerrank primarily contains programming problems harvested from programming competitions. Competitions where these problems are meant to be solved fast, with a time deadline. This means that the problems are more about building a quick, clever, solution and less about really learning the lessons that would help you in a programming career.
Another example of a solution is
string sep = "";
for (int i = d; a.Length + d - i > 0; i++) {
Console.Write(sep);
Console.Write(a[i % a.Length]);
sep = " ";
}
Which is, according to hackerranks estimation, "just as good" as the above solution, but is far less readable.
$endgroup$
$begingroup$
Well one thing one should certainly learn from this challenge is whatstring.Joindoes and how it avoids the rather awful for loop :) (The given solution also misses some necessary modulo ops)
$endgroup$
– Voo
5 hours ago
$begingroup$
@Voo Out of curiosity, which modulo does this miss? I know I wrote it by hand without the aid of a computer, but the loop (in my 5 element example, starting at index 3 would be 3, 4, 5, 6, 7 (8 would be 5 + 3 - 8, so it wouldn't get there). and 3 % 5 = 3, 4 % 5 = 4, 5 % 5 = 0, 6 % 5 = 1, 7 % 5 = 2. Now, I just might have a bug in there after all; but, maybe not, which is a perfect example of why writing it this way is less than ideal and whyhackerranks fascination with programming competitions as question banks is bad.
$endgroup$
– Edwin Buck
4 hours ago
1
$begingroup$
You're supposed to do n rotations. Nowhere does it say that n < arr.Length. You could have an array of1,2,3and d=5. Both of your solutions fail with an out of bounds there.
$endgroup$
– Voo
3 hours ago
add a comment |
$begingroup$
You are focusing on the wrong portion of the problem. You're thinking the array needs to be rotated. The output of the array needs to be "rotated" but the array can remain as-is.
So simply write a loop that starts at the middle of the array, incrementing until it hits the end, and then continues along from the beginning until it hits the index just before the one you started at.
The output of that loop is the "rotated" array, from the visibility of the testing framework.
string sep = "";
for (int i = d; i < a.Length; i++) {
Console.Write(sep);
Console.Write(a[i]);
sep = " ";
}
for (int i = 0; i < d; i++)
{
Console.Write(sep);
Console.Write(a[i]);
sep = " ";
}
This is a great reason why you should sometimes see hackerrank as a poor place to really learn programming.
hackerrank primarily contains programming problems harvested from programming competitions. Competitions where these problems are meant to be solved fast, with a time deadline. This means that the problems are more about building a quick, clever, solution and less about really learning the lessons that would help you in a programming career.
Another example of a solution is
string sep = "";
for (int i = d; a.Length + d - i > 0; i++) {
Console.Write(sep);
Console.Write(a[i % a.Length]);
sep = " ";
}
Which is, according to hackerranks estimation, "just as good" as the above solution, but is far less readable.
$endgroup$
You are focusing on the wrong portion of the problem. You're thinking the array needs to be rotated. The output of the array needs to be "rotated" but the array can remain as-is.
So simply write a loop that starts at the middle of the array, incrementing until it hits the end, and then continues along from the beginning until it hits the index just before the one you started at.
The output of that loop is the "rotated" array, from the visibility of the testing framework.
string sep = "";
for (int i = d; i < a.Length; i++) {
Console.Write(sep);
Console.Write(a[i]);
sep = " ";
}
for (int i = 0; i < d; i++)
{
Console.Write(sep);
Console.Write(a[i]);
sep = " ";
}
This is a great reason why you should sometimes see hackerrank as a poor place to really learn programming.
hackerrank primarily contains programming problems harvested from programming competitions. Competitions where these problems are meant to be solved fast, with a time deadline. This means that the problems are more about building a quick, clever, solution and less about really learning the lessons that would help you in a programming career.
Another example of a solution is
string sep = "";
for (int i = d; a.Length + d - i > 0; i++) {
Console.Write(sep);
Console.Write(a[i % a.Length]);
sep = " ";
}
Which is, according to hackerranks estimation, "just as good" as the above solution, but is far less readable.
answered 5 hours ago
Edwin BuckEdwin Buck
32414
32414
$begingroup$
Well one thing one should certainly learn from this challenge is whatstring.Joindoes and how it avoids the rather awful for loop :) (The given solution also misses some necessary modulo ops)
$endgroup$
– Voo
5 hours ago
$begingroup$
@Voo Out of curiosity, which modulo does this miss? I know I wrote it by hand without the aid of a computer, but the loop (in my 5 element example, starting at index 3 would be 3, 4, 5, 6, 7 (8 would be 5 + 3 - 8, so it wouldn't get there). and 3 % 5 = 3, 4 % 5 = 4, 5 % 5 = 0, 6 % 5 = 1, 7 % 5 = 2. Now, I just might have a bug in there after all; but, maybe not, which is a perfect example of why writing it this way is less than ideal and whyhackerranks fascination with programming competitions as question banks is bad.
$endgroup$
– Edwin Buck
4 hours ago
1
$begingroup$
You're supposed to do n rotations. Nowhere does it say that n < arr.Length. You could have an array of1,2,3and d=5. Both of your solutions fail with an out of bounds there.
$endgroup$
– Voo
3 hours ago
add a comment |
$begingroup$
Well one thing one should certainly learn from this challenge is whatstring.Joindoes and how it avoids the rather awful for loop :) (The given solution also misses some necessary modulo ops)
$endgroup$
– Voo
5 hours ago
$begingroup$
@Voo Out of curiosity, which modulo does this miss? I know I wrote it by hand without the aid of a computer, but the loop (in my 5 element example, starting at index 3 would be 3, 4, 5, 6, 7 (8 would be 5 + 3 - 8, so it wouldn't get there). and 3 % 5 = 3, 4 % 5 = 4, 5 % 5 = 0, 6 % 5 = 1, 7 % 5 = 2. Now, I just might have a bug in there after all; but, maybe not, which is a perfect example of why writing it this way is less than ideal and whyhackerranks fascination with programming competitions as question banks is bad.
$endgroup$
– Edwin Buck
4 hours ago
1
$begingroup$
You're supposed to do n rotations. Nowhere does it say that n < arr.Length. You could have an array of1,2,3and d=5. Both of your solutions fail with an out of bounds there.
$endgroup$
– Voo
3 hours ago
$begingroup$
Well one thing one should certainly learn from this challenge is what
string.Join does and how it avoids the rather awful for loop :) (The given solution also misses some necessary modulo ops)$endgroup$
– Voo
5 hours ago
$begingroup$
Well one thing one should certainly learn from this challenge is what
string.Join does and how it avoids the rather awful for loop :) (The given solution also misses some necessary modulo ops)$endgroup$
– Voo
5 hours ago
$begingroup$
@Voo Out of curiosity, which modulo does this miss? I know I wrote it by hand without the aid of a computer, but the loop (in my 5 element example, starting at index 3 would be 3, 4, 5, 6, 7 (8 would be 5 + 3 - 8, so it wouldn't get there). and 3 % 5 = 3, 4 % 5 = 4, 5 % 5 = 0, 6 % 5 = 1, 7 % 5 = 2. Now, I just might have a bug in there after all; but, maybe not, which is a perfect example of why writing it this way is less than ideal and why
hackerranks fascination with programming competitions as question banks is bad.$endgroup$
– Edwin Buck
4 hours ago
$begingroup$
@Voo Out of curiosity, which modulo does this miss? I know I wrote it by hand without the aid of a computer, but the loop (in my 5 element example, starting at index 3 would be 3, 4, 5, 6, 7 (8 would be 5 + 3 - 8, so it wouldn't get there). and 3 % 5 = 3, 4 % 5 = 4, 5 % 5 = 0, 6 % 5 = 1, 7 % 5 = 2. Now, I just might have a bug in there after all; but, maybe not, which is a perfect example of why writing it this way is less than ideal and why
hackerranks fascination with programming competitions as question banks is bad.$endgroup$
– Edwin Buck
4 hours ago
1
1
$begingroup$
You're supposed to do n rotations. Nowhere does it say that n < arr.Length. You could have an array of
1,2,3 and d=5. Both of your solutions fail with an out of bounds there.$endgroup$
– Voo
3 hours ago
$begingroup$
You're supposed to do n rotations. Nowhere does it say that n < arr.Length. You could have an array of
1,2,3 and d=5. Both of your solutions fail with an out of bounds there.$endgroup$
– Voo
3 hours ago
add a comment |
Ramakrishna is a new contributor. Be nice, and check out our Code of Conduct.
Ramakrishna is a new contributor. Be nice, and check out our Code of Conduct.
Ramakrishna is a new contributor. Be nice, and check out our Code of Conduct.
Ramakrishna is a new contributor. Be nice, and check out our Code of Conduct.
Thanks for contributing an answer to Code Review Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f214680%2fhacker-rank-array-left-rotation%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
3
$begingroup$
The best code is no code at all. Do you actually need to rotate the array, or just print the elements in rotated order? Because if that’s the case then you can save a whole lot of copying around.
$endgroup$
– Konrad Rudolph
12 hours ago
$begingroup$
From O(n^2) to O(n):
int n = d % a.Length; var b = a.Skip(n).Concat(a.Take(n)).ToArray();. You can always get rid of the lazy enumerable when its too slow.$endgroup$
– Caramiriel
11 hours ago
7
$begingroup$
@Caramiriel, you've got the wrong box. The one for answers is further down the page.
$endgroup$
– Peter Taylor
10 hours ago
1
$begingroup$
@Caramiriel this isn't
O(n)becauseSkipis not clever... as far as I know it iterates the collection to skip the items.$endgroup$
– t3chb0t
8 hours ago
2
$begingroup$
@t3chb0t Even if it goes through the array twice,
2n, or200nfor that matter, is stillO(n)$endgroup$
– TemporalWolf
6 hours ago