Spells and Charms

プログラミング(呪文学)の学習記録。

eloquent javascript 2nd edition chapter 4 Data Structures: Objects and Arrays

Exercises

The sum of a range

The sum of a range

 The introduction of this book alluded to the following as a nice way to compute the sum of a range of numbers:

 1
 
 
 

 Write a range function that takes two arguments, start and end, and returns an array containing all the numbers from start up to (and including) end.

 Next, write a sum function that takes an array of numbers and returns the sum of these numbers. Run the previous program and see whether it does indeed return 55.

 As a bonus assignment, modify your range function to take an optional third argument that indicates the “step” value used to build up the array. If no step is given, the array elements go up by increments of one, corresponding to the old behavior. The function call range(1, 10, 2) should return [1, 3, 5, 7, 9]. Make sure it also works with negative step values so that range(5, 2, -1) produces [5, 4, 3, 2].

 

 ひとつめのfunction.

function range(start,end){
var array=[];
  for(i=0; i<end-start+1; i++){
  array[i]= start+i;
}
  return array;
}

コンソール確認したら正しそうなので次に。

function sum(arr){
  var sumArray = 0
  for (var j = 0; j < arr.length; j++){
    sumArray += arr[j] 
  }
  return sumArray
}

これもコンソールで確認したら大丈夫そうだった。ので次。
次のはさっきかいたrangeをアレンジするもののよう。

 

ちょっと迷走。

 

 

できたっぽい!

function range(start,end,step){
  var array=[];
  if(step === undefined || null){
   step = 1
  }
  
  if(step<0){
   for(i=1; i<=start-end; i++){
    array[0] = start; 
    array[i] = array[i-1]+step;   
   }
 }else{
   for(i=1; i<=end-start; i++){
    array[0] = start; 
    array[i] = array[i-1]+step;   
   }
}
  return array;
}

function sum(arr){
  var sumArray = 0
  for (var j = 0; j < arr.length; j++){
    sumArray += arr[j] 
  }
  return sumArray
}

 

回答はpushをつかってましたが、

あまりまだ自分は多用してないのでforループで地道に書きました。

 

エクササイズはまだありますが、もうすぐテクニカルテストなるものを受けるので今回はここまでです。