zigzag conversion leetcode

The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility).

Screen Shot 2019-04-23 at 1.57.05 pm

Screen Shot 2019-04-23 at 1.58.22 pm.png

Here is the solution using nested while loop:

var convert = function(s, numRows) {
    if (numRows < 2) {
      return s;
    }
    var matrix = [];
    for (var i = 0; i < numRows; i++) {
        matrix.push([]);
    }
    var k = 0;
    var i = 0;
    var res = '';
    while (k < s.length) {
        while(i < matrix.length && k < s.length) {             
            matrix[i].push(s[k]);  // down            
             i++;             
             k++;         
         }         
         i = i-2;         
         while (i >= 0 && k < s.length) {
            matrix[i].push(s[k]) // up
            i--;
            k++;
        }
        i = i+2;
    }
    for (var i = 0; i < matrix.length; i++) {
        for (var k = 0; k < matrix[i].length; k++) {
            res += matrix[i][k];
        }
    }
   

 

Here is the solution mix while with for loop:

var convert = function(s, numRows) {
    var len = s.length;
    var matrix = [];

    var matrix = [];
    for (var i = 0; i < numRows; i++) {
        matrix.push([]);
    }

    var i = 0, res='';
    while(i < len) {
        for(var idx = 0; idx < numRows && i < len; idx++) { // down             
            matrix[idx].push(s[i]);// add it to the matrix              
            i++; // then increase          
         }         
        for(var idx = numRows - 2; idx >=1 && i< len; idx--){ //up
            matrix[idx].push(s[i++]); // another simple way and add the item then increase i
        }
    }

    for(var i = 0; i < matrix.length; i++){ 
        for(var j=0; j< matrix[i].length; j++){
                res += matrix[i][j];
        }
    }

    return res;
}

Node module require deep understand it

require.resolve(‘myModel’): this behaves exactly the same as require, but does not load the file. It will still throw an error if the file does not exist. This can be use for check an package is installed or not.

 

require(‘something’);

  1. try something.js
  2. try something.json
  3. try something.node

React and Redux Sagas Weather Report App Tutorial

Overview

In this tutorial we’re going to build a weather Report by using React Boilerplate . Few months ago I did a code testing by using angualr1.5 and now I like to do it again by using current popular tools react, redux and sagas.  React Boilerplate is not for beginner level, and I won’t explain any concept of react, redux, and sagas. There already has too many tutorial about it.

React Boilerplate is very mature start setup for  building scalable react app and suit for any complex real life project.

After finish that should look like this:

Screen Shot 2018-01-19 at 4.06.00 pm

Now let start it:

Part 1 – Setting up the base project and template.

  1. Create a folder, named “weather-react-redux-saga-app”
  2. cd weather-react-redux-saga-app
  3. run git clone https://github.com/react-boilerplate/react-boilerplate.git .
  4. npm run setup ( install the package and start the project.)
  5. npm run clean ( get rid of the template that react boilerplate provides)
  6. npm start ( now project setup done)

Part 2 – Create the container and components by  using React Boilerplate  provide component generate command. I will create one container component and two stateless component (WeaterListContainer and WeatherList stateless component and Weather component).

  1. run command ‘npm run generate container

move the arrow select React.component

what should it be called?

Do you want headers?

Do you want an actions/constants/selectors/reducer tuple for this container? y

Do you want sagas for asynchronous flows?y

Do you want i18n messages (i.e. will this component use text)?n

Do you want to load resources asynchronously?n

  2 . run command ‘npm run generate component

move the arrow select Stateless Function then enter

       What should it be called? WeatherList

Do you want i18n messages (i.e. will this component use text)?n

 Do you want to load the component asynchronously? n

  follow step 2 create Weather component.

  3. go to HomePage/index edit it using the WeatherListContainer

Screen Shot 2018-01-22 at 2.02.31 pm

Next post will explain how to working with api: openweathermap to get data by using saga and display it to the page.

to be continue….

 

Day of the Programmer

Marie invented a Time Machine and wants to test it by time-traveling to visit Russia on the Day of the Day of the Programmer (the 256th day of the year) during a year in the inclusive range from 1700 to 2700.

From 1700 to 2700, Russia’s official calendar was the Julian calendar; since 1919 they used the Gregorian calendar system. The transition from the Julian to Gregorian calendar system occurred in 1918, when the next day after January 31th was February 14 th . This means that in 1918, February 14th was the 32th day of the year in Russia.

In both calendar systems, February is the only month with a variable amount of days; it has 29 days during a leap year, and 28 days during all other years. In the Julian calendar, leap years are divisible by 4 ; in the Gregorian calendar, leap years are either of the following:

Divisible by 400.
Divisible by 4 and not divisible by 100.
Given a year, y, find the date of the 256th day of that year according to the official Russian calendar during that year. Then print it in the format dd.mm.yyyy, where dd is the two-digit day, mm is the two-digit month, and yyyy is y.

Input Format

A single integer denoting year y.

Constraints

Output Format

Print the full date of Day of the Programmer during year y in the format dd.mm.yyyy, where dd is the two-digit day, mm is the two-digit month, and yyyy is y.

Solution

process.stdin.resume();
process.stdin.setEncoding('ascii');

var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;

process.stdin.on('data', function (data) {
    input_stdin += data;
});

process.stdin.on('end', function () {
    input_stdin_array = input_stdin.split("\n");
    main();    
});

function readLine() {
    return input_stdin_array[input_currentline++];
}

/////////////// ignore above this line ////////////////////

function solve(year){
    if (year == 1918)
        return '26.09.1918'
    else if (((year  1918) && (year%400 == 0 || ((year%4 == 0) && (year%100 != 0)))))
        return '12.09.' + year
    else
        return '13.09.' + year
}

function main() {
    var year = parseInt(readLine());
    var result = solve(year);
    process.stdout.write(""+result+"\n");

}

Breaking the Records

Maria plays n games of college basketball in a season. Because she wants to go pro, she tracks her points scored per game sequentially in an array defined as score = [S0,S1,…,Sn-1] . After each game i , she checks to see if score Si breaks her record for most or least points scored so far during that season.

Given Maria’s array of scores for a season of n games, find and print the number of times she breaks her record for most and least points scored during the season.

Note: Assume her records for most and least points at the start of the season are the number of points scored during the first game of the season.

Input Format

The first line contains an integer denoting (the number of games).
The second line contains space-separated integers describing the respective values of .

 

 

Solution

process.stdin.resume();
process.stdin.setEncoding('ascii');

var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;

process.stdin.on('data', function (data) {
    input_stdin += data;
});

process.stdin.on('end', function () {
    input_stdin_array = input_stdin.split("\n");
    main();    
});

function readLine() {
    return input_stdin_array[input_currentline++];
}

/////////////// ignore above this line ////////////////////

function getRecord(s){
    // Complete this function
    var result = [];
    var countMax=0, countMin=0 ,max = s[0], min = s[0];
    for(var i=1; i max){ max = s[i];  countMax++; }
        if(s[i] < min){ min = s[i];  countMin++; }
    }
    result.push(countMax); 
    result.push(countMin);
    return result;
    
}

function main() {
    var n = parseInt(readLine());
    s = readLine().split(' ');
    s = s.map(Number);
    var result = getRecord(s);
    console.log(result.join(" "));

}

Between Two Sets

Consider two sets of positive integers,  and . We say that a positive integer, , is between sets  and  if the following conditions are satisfied:

  1. All elements in  are factors of .
  2.  is a factor of all elements in .

In other words, some  is between  and  if that value of  satisfies  for every  in  and also satisfies  for every  in . For example, if  and , then our possible  values are and .

Given  and , find and print the number of integers (i.e., possible ‘s) that are between the two sets.

Input Format

The first line contains two space-separated integers describing the respective values of  (the number of elements in set ) and  (the number of elements in set ).
The second line contains  distinct space-separated integers describing .
The third line contains  distinct space-separated integers describing .

Constraints

Output Format

Print the number of integers that are considered to be between  and .

Sample Input

2 3
2 4
16 32 96

Sample Output

3

Solution

process.stdin.resume();
process.stdin.setEncoding('ascii');

var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;

process.stdin.on('data', function (data) {
    input_stdin += data;
});

process.stdin.on('end', function () {
    input_stdin_array = input_stdin.split("\n");
    main();    
});

function readLine() {
    return input_stdin_array[input_currentline++];
}

/////////////// ignore above this line ////////////////////

function getTotalX(a, b) {
    var maxA = 0, minB = 101, count=0, n=a.length, m=b.length;

    for(var a_i=0; a_i  maxA ? tmpa : maxA;
    }

    for(var b_i=0; b_i < m; b_i++){
        var tmpb = b[b_i];
        minB = tmpb < minB ? tmpb : minB;
    }


  for(var i = maxA; i <= minB; i += maxA)
  {
      var factorA = true, factorB = true;
      //Check if all A are a factor of i
      for(var ii = 0; ii < n; ii++){
          if(i%a[ii] !=0){
              factorA = false;
              continue;
           }
      }

      //Check if i is a factor of all B
      for(var jj = 0; jj < m; jj++){
           if(b[jj]%i != 0){
              factorB = false;
              continue;
            }
      }
      
      if(factorA && factorB)
        count++;
  }
    
  return count;
    
}

function main() {
    var n_temp = readLine().split(' ');
    var n = parseInt(n_temp[0]);
    var m = parseInt(n_temp[1]);
    a = readLine().split(' ');
    a = a.map(Number);
    b = readLine().split(' ');
    b = b.map(Number);
    var total = getTotalX(a, b);
    process.stdout.write("" + total + "\n");

}

 

Apple and Orange

Sam’s house has an apple tree and an orange tree that yield an abundance of fruit. In the diagram below, the red region denotes his house, where  is the start point and  is the end point. The apple tree is to the left of his house, and the orange tree is to its right. You can assume the trees are located on a single point, where the apple tree is at point  and the orange tree is at point .

Apple and orange(2).png

When a fruit falls from its tree, it lands  units of distance from its tree of origin along the -axis. A negative value of  means the fruit fell  units to the tree’s left, and a positive value of  means it falls  units to the tree’s right.

Given the value of  for  apples and  oranges, can you determine how many apples and oranges will fall on Sam’s house (i.e., in the inclusive range )? Print the number of apples that fall on Sam’s house as your first line of output, then print the number of oranges that fall on Sam’s house as your second line of output.

Input Format

The first line contains two space-separated integers denoting the respective values of  and .
The second line contains two space-separated integers denoting the respective values of  and .
The third line contains two space-separated integers denoting the respective values of  and .
The fourth line contains  space-separated integers denoting the respective distances that each apple falls from point .
The fifth line contains  space-separated integers denoting the respective distances that each orange falls from point .

Constraints

Output Format

Print two lines of output:

  1. On the first line, print the number of apples that fall on Sam’s house.
  2. On the second line, print the number of oranges that fall on Sam’s house.

Sample Input 0

7 11
5 15
3 2
-2 2 1
5 -6

Sample Output 0

1
1

Explanation 0

The first apple falls at position .
The second apple falls at position .
The third apple falls at position .
The first orange falls at position .
The second orange falls at position .
Only one fruit (the second apple) falls within the region between  and , so we print  as our first line of output.
Only the second orange falls within the region between  and , so we print  as our second line of output.

Solution

process.stdin.resume();
process.stdin.setEncoding('ascii');

var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;

process.stdin.on('data', function (data) {
    input_stdin += data;
});

process.stdin.on('end', function () {
    input_stdin_array = input_stdin.split("\n");
    main();    
});

function readLine() {
    return input_stdin_array[input_currentline++];
}

/////////////// ignore above this line ////////////////////

function main() {
    var s_temp = readLine().split(' ');
    var s = parseInt(s_temp[0]);
    var t = parseInt(s_temp[1]);
    var a_temp = readLine().split(' ');
    var a = parseInt(a_temp[0]);
    var b = parseInt(a_temp[1]);
    var m_temp = readLine().split(' ');
    var m = parseInt(m_temp[0]);
    var n = parseInt(m_temp[1]);
    apple = readLine().split(' ');
    apple = apple.map(Number);
    orange = readLine().split(' ');
    orange = orange.map(Number);
    
    var countApple = 0;
    var countOrange = 0;
    apple.forEach(function(e) {
        if((a+e)>= s && (a+e)<=t) countApple++; }); orange.forEach(function(e) { if((b+e)>= s && (b+e)<=t)
           countOrange++;
    });
    
    process.stdout.write(countApple + "\n" + countOrange);
}

 

Grading Students

HackerLand University has the following grading policy:

  • Every student receives a  in the inclusive range from  to .
  • Any  less than  is a failing grade.

Sam is a professor at the university and likes to round each student’s  according to these rules:

  • If the difference between the  and the next multiple of  is less than , round  up to the next multiple of .
  • If the value of  is less than , no rounding occurs as the result will still be a failing grade.

For example,  will be rounded to  but  will not be rounded because the rounding would result in a number that is less than .

Given the initial value of  for each of Sam’s  students, write code to automate the rounding process. For each , round it according to the rules above and print the result on a new line.

Input Format

The first line contains a single integer denoting  (the number of students).
Each line  of the  subsequent lines contains a single integer, , denoting student ‘s grade.

Constraints

Output Format

For each  of the  grades, print the rounded grade on a new line.

Sample Input 0

4
73
67
38
33

Sample Output 0

75
67
40
33
Solution 

function solve(grades){
    var result = [];
    for(var i= 1; i<grades.length; i++){
       if(grades[i] < 38 || grades[i] % 5 <3)
          result.push(grades[i]);
       else
          result.push(grades[i] + (5- (grades[i] % 5)))
    }
    return result;
}

function main() {
    var n = parseInt(readLine());
    var grades = [];
    for(var grades_i = 0; grades_i < n; grades_i++){
       grades[grades_i] = parseInt(readLine());
    }
    var result = solve(grades);
    console.log(result.join("\n"));
}

Birthday Cake Candles

Colleen is turning  years old! Therefore, she has  candles of various heights on her cake, and candle  has height . Because the taller candles tower over the shorter ones, Colleen can only blow out the tallest candles.

Given the  for each individual candle, find and print the number of candles she can successfully blow out.

Input Format

The first line contains a single integer, , denoting the number of candles on the cake.
The second line contains  space-separated integers, where each integer  describes the height of candle .

Constraints

Output Format

Print the number of candles Colleen blows out on a new line.

Sample Input 0

4
3 2 1 3

Sample Output 0

2

Explanation 0

We have one candle of height , one candle of height , and two candles of height . Colleen only blows out the tallest candles, meaning the candles where . Because there are  such candles, we print  on a new line.

Solution Answer

process.stdin.resume();
process.stdin.setEncoding('ascii');

var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;

process.stdin.on('data', function (data) {
    input_stdin += data;
});

process.stdin.on('end', function () {
    input_stdin_array = input_stdin.split("\n");
    main();    
});

function readLine() {
    return input_stdin_array[input_currentline++];
}

/////////////// ignore above this line ////////////////////

function birthdayCakeCandles(n, ar) {
   
   var max=ar[0];
   var num=1;
 for (var i=1;i<n; i++){
   if (ar[i]>max){ 
      max=ar[i];
     num=1;
   }
   else if (ar[i]==max) num++;
   }
  return num;
    
}

function main() {
    var n = parseInt(readLine());
    ar = readLine().split(' ');
    ar = ar.map(Number);
    var result = birthdayCakeCandles(n, ar);
    process.stdout.write("" + result + "\n");

}

 

Full stack developer