Huawei OD computer-based test algorithm questions: The furthest footprint

Table of contents

Question part

Interpretation and analysis

Code


Question part

topic furthest footprint
difficulty easy
Question description An expedition team is responsible for exploring underground caves. When members of the expedition team carry out expedition missions, the recorders they carry will record their own coordinates from time to time, but other data will also be recorded during the recording intervals. After the exploration work is completed, the expedition team needs to obtain the farthest footprint position of a member relative to the expedition team headquarters during the expedition.
1. When the instrument records coordinates, the data format of the coordinates is (x, y), such as (1,2), (100,200), where 0<x<1000, 0<y<1000. There are illegal coordinates at the same time, such as (01,1), (1,01), (0,100), which are illegal coordinates.
If x = 0, y = 0 or the x and y values ​​have leading 0s (the first bit is 0), the coordinates are considered illegal. (Author's note)
2. Set the coordinates of the expedition headquarters as (0,0), and the distance between a certain position and the headquarters as: x * x + y * y.
3. If the distance between the two coordinates relative to the headquarters is the same, the coordinate reached first will be the farthest footprint.
4. If the coordinates in the recorder are not legal, output the headquarters coordinates (0,0).
Note: There is no need to consider double-level bracket nesting, such as sfsdfsd((1,2)).
Enter description A string representing the data in the logger.
For example: ferga13fdsf3(100,200)f2r3rfasf(300,400)
Output description A string representing the coordinates reached by the farthest footprint.
For example: (300,400)
Additional information none
------------------------------------------------------
Example
Example 1
enter ferg(3,10)a13fdsf3(3,4)f2r3rfasf(5,10)
output (5,10)
illustrate There are three legal coordinates in the recorder: (3,10), (3,4), (5,10), among which (5,10) is the coordinate farthest from the headquarters, and output (5,10).
Example 2
enter asfefaweawfaw(0,1)fe
output (0,0)
illustrate The coordinates in the recorder are not legal, and the headquarters coordinates (0,0) are output.


Interpretation and analysis

Question interpretation :

This question requires filtering out all legal coordinates from the input string , calculating the farthest coordinate, and outputting it. The meaning of legal coordinates is:
1. The first letter is '(', the last letter is ')', and there are two numbers in the middle, separated by ','.
2. The first digit of both numbers cannot be 0 (the number cannot be equal to 0, and the number greater than 0 cannot have leading 0). 
If there are no legal coordinates, (0,0) is output .

There is no clear statement about the legality of coordinates in this question. It can only be summarized through the example of the question.
A good topic should use general language to describe legal (or illegal) situations and then provide examples. Otherwise, examples will be ambiguous if they do not cover all scenarios.

Analysis and ideas :

First set two variables:
1. maxPosition, string type, used to record the farthest coordinates, the initial value is "(0,0)".
2. maxDistance, an integer number, records the farthest distance, and the initial value is 0.

Traverse the string. During the process of traversing the string, after finding a legal coordinate , calculate the distance to the headquarters and set it as tmpDistance. If tmpDistance is greater than maxDistance, assign it to maxDistance and assign its coordinate to maxPosition. Continue traversing the string, looking for the next legal coordinate, and looping to determine the distance to the headquarters until the end of the string.

When calculating the distance to the headquarters , assuming that the coordinates are (x,y), the distance is sqrt(x * x + y * y). Since this question only cares about the relative distance of coordinates and does not require absolute values, x * x + y * y can be used instead of its square root value for comparison to reduce the amount of calculation.

The string representing legal coordinates must meet the following conditions after removing the first parentheses:
1. Some position in the middle (neither the first letter nor the last letter) contains the character ','.
2. Separate it into two strings by the delimiter ','. The first letter of these two strings is not 0, and both of them can be parsed into positive integers.

This algorithm only needs to traverse the string once, the time complexity is O(n), uses 2 additional primitive data type variables, and the space complexity is O(1).


Code

Java code

import java.util.Scanner;

/**
 * 最远足迹
 * 
 * @since 2023.09.07
 * @version 0.1
 * @author Frank
 *
 */
public class MaxDistance {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String record = sc.nextLine();

		int i = 0;
		int maxDistance = 0;
		String maxPosition = "(0,0)";
		while (i < record.length()) {
			int leftPT = record.indexOf('(', i);
			int rightPT = record.indexOf(')', i);

			if (leftPT < 0) {
				break;
			}

			String position = record.substring(leftPT + 1, rightPT);
			int tmpDistance = getDistance(position);
			if (tmpDistance > maxDistance) {
				maxDistance = tmpDistance;
				maxPosition = "(" + position + ")";
			}
			i = rightPT + 1;
		}
		System.out.println(maxPosition);
	}

	private static int getDistance(String position) {
		int ret = 0;
		String[] posArr = position.split(",");
		if (posArr == null || posArr.length != 2) {
			return 0;
		}
		for (int i = 0; i < posArr.length; i++) {
			String strPos = posArr[i];
			if (strPos.length() == 0 || strPos.startsWith("0")) {
				return 0;
			}
			try {
				int intPos = Integer.parseInt(strPos);
				ret += (intPos * intPos);
			} catch (NumberFormatException e) {
				return 0;
			}

		}

		return ret;
	}

}

JavaScript code

const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;

function getDistance( position ) {
    var ret = 0;
    var posArr = position.split(",");
    if (posArr == null || posArr.length != 2) {
        return 0;
    }
    for (var i = 0; i < posArr.length; i++) {
        var strPos = posArr[i];
        if (strPos.length == 0 || strPos.startsWith("0")) {
            return 0;
        }
        var intPos = Number(strPos);
        if( Number.isNaN( intPos) )
        {
            return 0;
        }
        ret += (intPos * intPos);

    }

    return ret;
}

function processInput( line )
{
    var record = line;
    var i = 0;
    var maxDistance = 0;
    var maxPosition = "(0,0)";
    if( !record )
    {
        console.log(maxPosition);
        return;
    }
    while (i < record.length) {
        var leftPT = record.indexOf('(', i);
        var rightPT = record.indexOf(')', i);

        if (leftPT < 0) {
            break;
        }

        var position = record.substring(leftPT + 1, rightPT);
        var tmpDistance = getDistance(position);
        if (tmpDistance > maxDistance) {
            maxDistance = tmpDistance;
            maxPosition = "(" + position + ")";
        }
        i = rightPT + 1;
    }
    console.log(maxPosition);
}

void async function() {
    let input = [];
    while (line = await readline()) {
        processInput( line );
    }

}();

(over)

Guess you like

Origin blog.csdn.net/ZiJinShi/article/details/132734425