Niklaus Wirth

Niklaus Wirth

Translate

(29)Map the Debris


день программы "#100 Days Of Code"
Return a new array that transforms the element's average altitude into their orbital periods.
The array will contain objects in the format {name: 'name', avgAlt: avgAlt}.
You can read about orbital periods on wikipedia.
The values should be rounded to the nearest whole number. The body being orbited is Earth.
The radius of the earth is 6367.4447 kilometers, and the GM value of earth is 398600.4418 km3s-2.



Here are some helpful links:

function orbitalPeriod(arr) {
 var GM = 398600.4418;
  var earthRadius = 6367.4447;
var answer =[];

  var radius;
  
  for (var i = 0; i < arr.length; i++){
    answer[i]= {};
   answer[i].name = arr[i].name;
    
    radius =earthRadius + arr[i].avgAlt;
    answer[i].orbitalPeriod = Math.round(2 * Math.PI *Math.sqrt((Math.pow(radius,3))/GM));

}
return answer;

}

orbitalPeriod([{name : "sputnik", avgAlt : 35873.5553}]);



Ответы:
orbitalPeriod([{name : "sputnik", avgAlt : 35873.5553}])
return [{name: "sputnik", orbitalPeriod: 86400}].

orbitalPeriod([{name: "iss", avgAlt: 413.6}, {name: "hubble", avgAlt: 556.7}, {name: "moon", avgAlt: 378632.553}])
return [{name : "iss", orbitalPeriod: 5557}, {name: "hubble", orbitalPeriod: 5734}, {name: "moon", orbitalPeriod: 2377399}].

(28)Make a Person

Make a Person
28-ой день программы "#100 Days Of Code"

Fill in the object constructor with the following methods below:

getFirstName()
getLastName()
getFullName()
setFirstName(first)
setLastName(last)
setFullName(firstAndLast)

Run the tests to see the expected output for each method.

The methods that take an argument must accept only one argument and it has to be a string.

These methods must be the only available means of interacting with the object.

Here are some helpful links:



var Person = function(firstAndLast) {
  var namesArr = firstAndLast.split(" ");
  
  this.getFirstName = function(){
    return namesArr[0];
  };
  this.getLastName = function(){
    return namesArr[1];
  };
  this.getFullName = function(){
    return namesArr.join(" ");
  };
  this.setFirstName = function(first){
    namesArr[0] = first;
  };
  this.setLastName = function(last){
    namesArr[1] = last;
  };
  this.setFullName = function(firstAndLast){
    namesArr = firstAndLast.split(' ');
  };
    return firstAndLast;
};

var bob = new Person('Bob Ross');
bob.getFullName();




(27)Friendly Date Ranges


27-ой день программы "#100 Days Of Code"

Convert a date range consisting of two dates formatted as YYYY-MM-DD into a more readable format.

The friendly display should use month names instead of numbers and ordinal dates instead of cardinal (1st instead of 1).

Do not display information that is redundant or that can be inferred by the user: if the date range ends in less than a year from when it begins, do not display the ending year.

Additionally, if the date range begins in the current year (i.e. it is currently the year 2016) and ends within one year, the year should not be displayed at the beginning of the friendly range.

If the range ends in the same month that it begins, do not display the ending year or month.

Examples:

makeFriendlyDates(["2016-07-01", "2016-07-04"]) should return ["July 1st","4th"]

makeFriendlyDates(["2016-07-01", "2018-07-04"]) should return ["July 1st, 2016", "July 4th, 2018"].



function makeFriendlyDates(str) {
   
 
  var months = ['January','February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
  
   function convertDate(str) {
    var dateStr = str.split('-');
    return (new Date(Date.UTC(dateStr[0], dateStr[1] - 1, dateStr[2])));

  }
  var dateA = convertDate(str[0]);
  var dateB = convertDate(str[1]);
  
  function dayEnd (val){
   if(val==1 || val ==21 || val == 31){
     return val +'st';
   }else if(val == 2 || val == 22){
     return val + 'nd';
   } else if(val == 3 || val == 33){
     return val +'rd';
   }else{
     return val + 'th';
   }
  }

   function monthDiff(dateA, dateB) {
    var monthB = dateB.getUTCFullYear() * 12 + dateB.getUTCMonth();
    var monthA = dateA.getUTCFullYear() * 12 + dateA.getUTCMonth();
    return monthB - monthA;
  }

  
  function dayDiff(dateA, dateB) {
    if(dateB.getUTCMonth() === dateA.getUTCMonth()){
      return dateA.getUTCDate()-dateB.getUTCDate();
    }
    return 0;
  }

  
  function getMonth(date) {
    return months[date.getUTCMonth()];
  }
 


  
 function displayDate() {

   
    if (dateB.getTime() - dateA.getTime() === 0) {
      return [getMonth(dateA) + ' ' + dayEnd(dateA.getUTCDate()) + ', ' + dateA.getUTCFullYear()];
    }

    
    if (dateA.getUTCMonth() === dateB.getUTCMonth() && dateA.getUTCFullYear() === dateB.getUTCFullYear()) {
      return [getMonth(dateA) + ' ' + dayEnd(dateA.getUTCDate()), dayEnd(dateB.getUTCDate())];
    }

    
    if (monthDiff(dateA, dateB) < 12 && dateA.getUTCFullYear() !== dateB.getUTCFullYear() ) {
      return [getMonth(dateA) + ' ' + dayEnd(dateA.getUTCDate()), getMonth(dateB) + ' ' + dayEnd(dateB.getUTCDate())];
    }

    
    if (monthDiff(dateA, dateB) <= 12 && dayDiff(dateA, dateB)>0) {
      return [getMonth(dateA) + ' ' + dayEnd(dateA.getUTCDate())+', '+dateA.getUTCFullYear(), getMonth(dateB) + ' ' + dayEnd(dateB.getUTCDate())];
    }

    if (monthDiff(dateA, dateB) < 12) {
      return [getMonth(dateA) + ' ' + dayEnd(dateA.getUTCDate())+', '+dateA.getUTCFullYear(), getMonth(dateB) + ' ' + dayEnd(dateB.getUTCDate())];
    }

   
    return [getMonth(dateA) + ' ' + dayEnd(dateA.getUTCDate()) + ', ' + dateA.getUTCFullYear(), getMonth(dateB) + ' ' + dayEnd(dateB.getUTCDate()) + ', ' + dateB.getUTCFullYear()];
  }
  
  

  return displayDate();
}

makeFriendlyDates(['2016-07-01', '2016-07-04']);



Ответы:

makeFriendlyDates(["2016-07-01", "2016-07-04"])
return ["July 1st","4th"].

makeFriendlyDates(["2016-12-01", "2017-02-03"])
return ["December 1st","February 3rd"].

makeFriendlyDates(["2016-12-01", "2018-02-03"])
return ["December 1st, 2016","February 3rd, 2018"].

makeFriendlyDates(["2017-03-01", "2017-05-05"])
return ["March 1st, 2017","May 5th"]

makeFriendlyDates(["2018-01-13", "2018-01-13"])
return ["January 13th, 2018"].

makeFriendlyDates(["2022-09-05", "2023-09-04"])
return ["September 5th, 2022","September 4th"].

makeFriendlyDates(["2022-09-05", "2023-09-05"])
return ["September 5th, 2022","September 5th, 2023"].


(26) No repeats please

No repeats please
26-ой день программы "#100 Days Of Code"

Return the number of total permutations of the provided string that don't have repeated consecutive letters. Assume that all characters in the provided string are each unique.

For example, aab should return 2 because it has 6 total permutations (aab, aab, aba, aba, baa, baa), but only 2 of them (aba and aba) don't have the same letter (in this case a) repeating.

Более подробно о первом варианте решения, можно прочитать здесь! macengr.wordpress.com



function permAlone(str) {
 
  if(str.length===0){
    return 1;
  }
   var amount=0;
  for(var i = 0; i < str.length; i++){
    if(str[i]!== arguments[1]){
      amount +=permAlone(str.substring(0,i)+str.substring(i+1),str[i]);
      
    }
  }
  return amount;
}

permAlone('aab');



Using a Heap Algorithm to generate all permutations


function permAlone(str) {
  
  var arr = str.split('');
  var permutations = [];
  var regex = /(.)\1+/g;
  
  function swap(index1, index2) {
    var aux = arr[index1];
    arr[index1] = arr[index2];
    arr[index2] = aux;
  }
  
  function generate(int) {
    if (int === 1) {
      permutations.push(arr.join(''));
    } else {
      for (var i = 0; i < int - 1; i++) {
        generate(int - 1);
        if (int % 2 === 0) {
          swap(i, int-1);
        } else {
          swap(0, int-1);
        }
      }
      generate(int - 1);
    }  
  }      
  
  generate(arr.length);
  
  var filtered = permutations.filter(function(string) {
    return !string.match(regex);
  });
  
  return filtered.length;

Ответы:

permAlone("aab")
return a number.

permAlone("aab")
return 2.

permAlone("aaa")
return 0.

permAlone("aabb")
return 8.

permAlone("abcdefa")
return 3600.

permAlone("abfdefa")
return 2640.

permAlone("zzzzzzzz")
return 0.

permAlone("a")
return 1.

permAlone("aaab")
return 0.

permAlone("aaabb")
return 12.


(25) Inventory Update

Inventory Update
25-ый день программы "#100 Days Of Code"

Compare and update the inventory stored in a 2D array against a second 2D array of a fresh delivery. Update the current existing inventory item quantities (in arr1). If an item cannot be found, add the new item and quantity into the inventory array. The returned inventory array should be in alphabetical order by item.



function updateInventory(arr1, arr2) {
    // All inventory must be accounted for or you're fired!
  for(var i = 0; i < arr1.length; i++){
    for(var j = 0; j < arr2.length; j++){
     if(arr1[i][1] ===arr2[j][1]){
       arr1[i][0] += arr2[j][0];
         arr2.splice(j, 1);
          j--;
     }     
   }
  }
   arr1 = arr1.concat(arr2); 
  arr1.sort(function(a,b){
    return a[1] > b[1];
  });
    return arr1;
}

// Example inventory lists
var curInv = [
    [21, "Bowling Ball"],
    [2, "Dirty Sock"],
    [1, "Hair Pin"],
    [5, "Microphone"]
];

var newInv = [
    [2, "Hair Pin"],
    [3, "Half-Eaten Apple"],
    [67, "Bowling Ball"],
    [7, "Toothpaste"]
];

updateInventory(curInv, newInv);



Ответы:

The function updateInventory
return an array.

updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]]).length
return an array with a length of 6.

updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]])
return [[88, "Bowling Ball"], [2, "Dirty Sock"], [3, "Hair Pin"], [3, "Half-Eaten Apple"], [5, "Microphone"], [7, "Toothpaste"]].

updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [])
return [[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]].

updateInventory([], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]])
return [[67, "Bowling Ball"], [2, "Hair Pin"], [3, "Half-Eaten Apple"], [7, "Toothpaste"]].

updateInventory([[0, "Bowling Ball"], [0, "Dirty Sock"], [0, "Hair Pin"], [0, "Microphone"]], [[1, "Hair Pin"], [1, "Half-Eaten Apple"], [1, "Bowling Ball"], [1, "Toothpaste"]])
return [[1, "Bowling Ball"], [0, "Dirty Sock"], [1, "Hair Pin"], [1, "Half-Eaten Apple"], [0, "Microphone"], [1, "Toothpaste"]].


(24)Exact Change

Exact Change
24-ый день программы "#100 Days Of Code"

Design a cash register drawer function checkCashRegister() that accepts purchase price as the first argument (price), payment as the second argument (cash), and cash-in-drawer (cid) as the third argument.

cid is a 2D array listing available currency.

Return the string "Insufficient Funds" if cash-in-drawer is less than the change due. Return the string "Closed" if cash-in-drawer is equal to the change due.

Otherwise, return change in coin and bills, sorted in highest to lowest order.




function checkCashRegister(price, cash, cid) {
  var change=[];
  // Here is your change, ma'am.
 var money =[["PENNY", 1], ["NICKEL", 5], ["DIME", 10], ["QUARTER", 25], ["ONE", 100], ["FIVE", 500], ["TEN", 1000], ["TWENTY", 2000], ["ONE HUNDRED", 10000]];
  var debt = cash * 100 - price*100;
  var cashInDrawer = 0;
  var rating = 0;
  
  for(i = money.length - 1; i >= 0; i--){
    cid[i][1] = Math.round(cid[i][1] * 100);
    cashInDrawer += cid[i][1];
    rating = 0;
    if(debt >= money[i][1]){
      while(cid[i][1] - money[i][1] >= 0){
        if(debt - money[i][1] >= 0){
          cid[i][1] -= money[i][1];
          debt -=money[i][1];
          cashInDrawer -= money[i][1];
          rating += money[i][1];
        } else {
          break;
        }
      }
      change.push([money[i][0], rating/100]);
    }
  }
  
  if(debt > 0){
    return "Insufficient Funds";
  } else if(cashInDrawer === 0){
    return "Closed";
  }
  return change;
}

// Example cash-in-drawer array:
// [["PENNY", 1.01],
// ["NICKEL", 2.05],
// ["DIME", 3.10],
// ["QUARTER", 4.25],
// ["ONE", 90.00],
// ["FIVE", 55.00],
// ["TEN", 20.00],
// ["TWENTY", 60.00],
// ["ONE HUNDRED", 100.00]]

checkCashRegister(19.50, 20.00, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.10], ["QUARTER", 4.25], ["ONE", 90.00], ["FIVE", 55.00], ["TEN", 20.00], ["TWENTY", 60.00], ["ONE HUNDRED", 100.00]]);



Ответы:

checkCashRegister(19.50, 20.00, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.10], ["QUARTER", 4.25], ["ONE", 90.00], ["FIVE", 55.00], ["TEN", 20.00], ["TWENTY", 60.00], ["ONE HUNDRED", 100.00]])
return an array.

checkCashRegister(19.50, 20.00, [["PENNY", 0.01], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]])
return a string.

checkCashRegister(19.50, 20.00, [["PENNY", 0.50], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]])
return a string.

checkCashRegister(19.50, 20.00, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.10], ["QUARTER", 4.25], ["ONE", 90.00], ["FIVE", 55.00], ["TEN", 20.00], ["TWENTY", 60.00], ["ONE HUNDRED", 100.00]])
return [["QUARTER", 0.50]].

checkCashRegister(3.26, 100.00, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.10], ["QUARTER", 4.25], ["ONE", 90.00], ["FIVE", 55.00], ["TEN", 20.00], ["TWENTY", 60.00], ["ONE HUNDRED", 100.00]])
return [["TWENTY", 60.00], ["TEN", 20.00], ["FIVE", 15.00], ["ONE", 1.00], ["QUARTER", 0.50], ["DIME", 0.20], ["PENNY", 0.04]].

checkCashRegister(19.50, 20.00, [["PENNY", 0.01], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]])
return "Insufficient Funds".

checkCashRegister(19.50, 20.00, [["PENNY", 0.01], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 1.00], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]])
return "Insufficient Funds".

checkCashRegister(19.50, 20.00, [["PENNY", 0.50], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]])
return "Closed".


(23)Symmetric Difference

(23)Symmetric Difference
23-ий день программы "#100 Days Of Code"



function sym(args) {
  return Array.prototype.reduce.call(arguments,(a,b)=>a.filter(c=>b.every(d=>c!=d)).concat(b.filter(c=>a.every(d=>c!=d))),[]).filter((e,i,a)=>a.indexOf(e)===i);
}

sym([1, 2, 3], [5, 2, 1, 4]);



const sym = (...args) => {    
  return args.reduce((acc, curr) => {
    // change curr to hold unique values
    const set = new Set(curr)
    curr = Array.from(set)
    
    return acc.filter(a => !curr.includes(a)).concat(curr.filter(b => !acc.includes(b)))
  }, [])
}

sym([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5])

Ответы:

sym([1, 2, 3], [5, 2, 1, 4])
return [3, 4, 5].

sym([1, 2, 3], [5, 2, 1, 4])
contain only three elements.

sym([1, 2, 5], [2, 3, 5], [3, 4, 5])
return [1, 4, 5]

sym([1, 2, 5], [2, 3, 5], [3, 4, 5])
contain only three elements.

sym([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5])
return [1, 4, 5].

sym([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5])
contain only three elements.

sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3])
return [2, 3, 4, 6, 7].

sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3])
contain only five elements.

sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3], [5, 3, 9, 8], [1])
return [1, 2, 4, 5, 6, 7, 8, 9].

sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3], [5, 3, 9, 8], [1])
contain only eight elements.