Sunday, August 24, 2014

Code Hunt Solutions 2

2.01 - int [] a = new int [n];
for(int i = 0; i < n; i++){
a [i] = i;
}
return a;
2.02 -  int [] a = new int [n];
for(int i = 0; i < n; i++){
a [i] = i*n;
}

return a;
2.03 -  int [] a = new int [n];
  for(int i = 0; i < n; i++){
  a [i] = i*i;
  }

  return a;
2.04 - int result = 0;
foreach(var i in v){
result += i;
}

return result;
2.05 - int r = 0;
for(int i = 0; i < n; i++)
r += (i*i);

return r;
2.06 -  int count = 0;
foreach(char c in s){
if (c == 'a'){
count++;
}
}
return count;
2.07 - int r = 0;
foreach(char x in string s){
r++;
}
return r;

13 comments:

  1. 02.04: need in code shape

    ReplyDelete
  2. 02.06 Also need in code shape

    ReplyDelete
  3. for 2.01 the 3 point solution is

    Enumerable.Range(0, n).ToArray();

    You'll have to add System.Linq

    ReplyDelete
  4. 2.02 - 3 point solution:
    System.Linq
    Enumerable.Range(0, n).ToArray().Select(x => (x * n)).ToArray();

    ReplyDelete
  5. 02.04
    return v.Aggregate((sum, i) => unchecked(sum + i));

    ReplyDelete
  6. 02.06 the elegant solution is:
    using System.Text.RegularExpressions;
    return Regex.Matches(s, "a").Count;

    ReplyDelete
  7. Similarly, 02.07 is:
    using System.Text.RegularExpressions;
    return Regex.Matches(s, x.ToString()).Count;

    ReplyDelete
  8. This comment has been removed by the author.

    ReplyDelete
  9. 2.04
    int result = 0;
    for(int i:v){
    result += i;
    }

    ReplyDelete
  10. Efficient method for 2.06


    return s.length()-s.replace(a,"").length();

    ReplyDelete