解决方案电影标题中缺少代码的片段,完成挑战更多[关闭]
Posted
技术标签:
【中文标题】解决方案电影标题中缺少代码的片段,完成挑战更多[关闭]【英文标题】:Fragment of missing code in the solution Movie Titles, complete a challenge more [closed] 【发布时间】:2018-07-05 00:43:31 【问题描述】:要解决这个难题,请编写一个 HTTP GET 方法来从特定电影数据库中检索信息。完成编辑器中的功能;它有一个参数:一个字符串,substr。该函数必须执行以下任务:
-
查询https://jsonmock.hackerrank.com/api/movies/search/?Title=substr(其中substr 是substr 的值)。来自网站的查询响应是一个 JSON 响应,包含以下五个字段:
• page:当前页面。
• per_page:每页的最大结果数。
• total:标题中包含子字符串 substr 的此类电影的总数。
• total_pages:获得所有结果必须查询的总页数。
• 数据:包含电影信息的 JSON 对象数组,其中 Title 字段表示电影的标题。请注意,此字段是分页的,因此,为了合并分页,您必须查询 https://jsonmock.hackerrank.com/api/movies/search/?Title=substr&page=pageNumber,其中 pageNumber 是一个整数,表示您要查看的页面(例如,1、2 等)。
创建一个名为titles 的字符串数组来存储总元素。对于每一页结果,将每部电影的标题存储在标题数组中。
按升序对标题进行排序并将其作为您的答案返回。
输入格式
单个字符串 substr,表示您必须查询的子字符串。
输出格式
返回一个字符串数组,该数组对应于标题中带有 susbtr 的电影标题,按升序排序。
示例输入 0
蜘蛛侠
样本输出 0
神奇蜘蛛侠综合症 战斗、飞行和驾驶:蜘蛛侠 3 的特技 好莱坞的讲故事大师:现场蜘蛛侠 意大利蜘蛛侠 蜘蛛侠 蜘蛛侠 蜘蛛侠5 蜘蛛侠和奶奶 蜘蛛侠在戛纳 超人、蜘蛛侠或蝙蝠侠 超凡蜘蛛侠 T4 首映特辑 蜘蛛侠之死 他们叫我蜘蛛侠解释0
对于这个例子,我们想要所有包含子字符串蜘蛛侠的电影标题。查询https://jsonmock.hackerrank.com/api/movies/search/?Title=spiderman&page=1 的响应是:
"page": "1",
"per_page": 10,
"total": 13,
"total_pages": 2,
"data": [
"Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BYjFhN2RjZTctMzA2Ni00NzE2LWJmYjMtNDAyYTllOTkyMmY3XkEyXkFqcGdeQXVyNTA0OTU0OTQ@._V1_SX300.jpg",
"Title": "Italian Spiderman",
"Type": "movie",
"Year": "2007",
"imdbID": "tt2705436"
,
"Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BMjQ4MzcxNDU3N15BMl5BanBnXkFtZTgwOTE1MzMxNzE@._V1_SX300.jpg",
"Title": "Superman, Spiderman or Batman",
"Type": "movie",
"Year": "2011",
"imdbID": "tt2084949"
,
"Poster": "N/A",
"Title": "Spiderman",
"Type": "movie",
"Year": "1990",
"imdbID": "tt0100669"
,
"Poster": "N/A",
"Title": "Spiderman",
"Type": "movie",
"Year": "2010",
"imdbID": "tt1785572"
,
"Poster": "N/A",
"Title": "Fighting, Flying and Driving: The Stunts of Spiderman 3",
"Type": "movie",
"Year": "2007",
"imdbID": "tt1132238"
,
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjE3Mzg0MjAxMl5BMl5BanBnXkFtZTcwNjIyODg5Mg@@._V1_SX300.jpg",
"Title": "Spiderman and Grandma",
"Type": "movie",
"Year": "2009",
"imdbID": "tt1433184"
,
"Poster": "N/A",
"Title": "The Amazing Spiderman T4 Premiere Special",
"Type": "movie",
"Year": "2012",
"imdbID": "tt2233044"
,
"Poster": "N/A",
"Title": "Amazing Spiderman Syndrome",
"Type": "movie",
"Year": "2012",
"imdbID": "tt2586634"
,
"Poster": "N/A",
"Title": "Hollywood's Master Storytellers: Spiderman Live",
"Type": "movie",
"Year": "2006",
"imdbID": "tt2158533"
,
"Poster": "N/A",
"Title": "Spiderman 5",
"Type": "movie",
"Year": "2008",
"imdbID": "tt3696826"
]
查询https://jsonmock.hackerrank.com/api/movies/search/?Title=spiderman&page=2的响应是:
"page": "2",
"per_page": 10,
"total": 13,
"total_pages": 2,
"data": [
"Poster": "N/A",
"Title": "They Call Me Spiderman",
"Type": "movie",
"Year": "2016",
"imdbID": "tt5861236"
,
"Poster": "N/A",
"Title": "The Death of Spiderman",
"Type": "movie",
"Year": "2015",
"imdbID": "tt5921428"
,
"Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BZDlmMGQwYmItNTNmOS00OTNkLTkxNTYtNDM3ZWVlMWUyZDIzXkEyXkFqcGdeQXVyMTA5Mzk5Mw@@._V1_SX300.jpg",
"Title": "Spiderman in Cannes",
"Type": "movie",
"Year": "2016",
"imdbID": "tt5978586"
]
每个响应页面中每部电影的 Title 字段各自的值是:
意大利蜘蛛侠 超人、蜘蛛侠或蝙蝠侠 蜘蛛侠 蜘蛛侠 战斗、飞行和驾驶:蜘蛛侠 3 的特技 蜘蛛侠和奶奶 超凡蜘蛛侠 T4 首映特辑 神奇蜘蛛侠综合症 好莱坞的讲故事大师:现场蜘蛛侠 蜘蛛侠5 他们叫我蜘蛛侠 蜘蛛侠之死 蜘蛛侠在戛纳然后我们将每个标题存储在我们的标题数组中,按升序对其进行排序,并将其作为我们的答案返回。
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
import java.net.*;
import com.google.gson.*;
public class Solution
/*
* Complete the function below.
*/
static String[] getMovieTitles(String substr)
//complete function here
public static void main(String[] args) throws IOException
Scanner in = new Scanner(System.in);
final String fileName = System.getenv("OUTPUT_PATH");
BufferedWriter bw = new BufferedWriter(new FileWriter(fileName));
String[] res;
String _substr;
try
_substr = in.nextLine();
catch (Exception e)
_substr = null;
res = getMovieTitles(_substr);
for(int res_i=0; res_i < res.length; res_i++)
bw.write(String.valueOf(res[res_i]));
bw.newLine();
bw.close();
【问题讨论】:
问题是什么? 我应该在允许我编译代码的函数中放入什么,我是 java 新手,我找到了这个练习,但我不知道该怎么做。 人们在面试和考试中作弊,然后在一个月后被解雇时抱怨。 你真的发布了一个hackerrank问题并且你有所有这些SO点吗?这里有点想念 【参考方案1】:这就是你要找的:
String[] getMovieTitles(String substr)
String response;
int startPage = 1;
int totalPages = Integer.MAX_VALUE;
List<String> titles = new ArrayList<>();
while (startPage <= totalPages)
try
URL obj = new URL("https://jsonmock.hackerrank.com/api/movies/search/?Title=" + substr + "&page=" + startPage);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
while ((response = in.readLine()) != null)
JsonObject convertedObject = new Gson().fromJson(response, JsonObject.class);
totalPages = convertedObject.get("total_pages").getAsInt();
JsonArray data = convertedObject.getAsJsonArray("data");
for (int i = 0; i < data.size(); i++)
String title = data.get(i).getAsJsonObject().get("Title").getAsString();
titles.add(title);
in.close();
startPage++;
catch (Exception ex)
ex.printStackTrace();
Collections.sort(titles);
return titles.toArray(new String[0]);
【讨论】:
【参考方案2】:这是一个 javascript 答案。
var https = require('https');
function fetchData(substr)
pageNum = 1;
let url = 'https://jsonmock.hackerrank.com/api/movies/search/?Title=' + substr + "&page=" + pageNum;
https.get(url, (res) =>
res.setEncoding('utf8');
res.on('data', function(body)
let dataRec = JSON.parse(body);
let movies = dataRec.data;
let totPages = dataRec.total_pages;
let sortArray = [];
movies.map((a) =>
sortArray.push(a.Title)
)
for (let i = 2; i <= totPages; i++)
let newPage = i;
let url1 = 'https://jsonmock.hackerrank.com/api/movies/search/?Title=' + substr + "&page=" + newPage;
https.get(url1, (res) =>
res.setEncoding('utf8');
res.on('data', function(body)
let newData = JSON.parse(body);
let newMovies = newData.data;
for (let i = 0; i < newMovies.length; i++)
sortArray.push(newMovies[i].Title);
console.log(sortArray.sort());
)
)
)
)
//primary function
function getMovieTitles(substr)
fetchData(substr);
getMovieTitles("spiderman");
【讨论】:
【参考方案3】:这是另一个带有承诺的a2441918 版本!!!。
"use strict";
const https = require("https");
const getMovieTitlesData = (title, page = 1) =>
const url = `https://jsonmock.hackerrank.com/api/movies/search/?Title=$encodeURI(
title
)&page=$page`;
const titles = [];
return new Promise((resolve, reject) =>
https
.get(url, function(res)
let body = "";
res.setEncoding("utf-8");
res.on("data", function(chunk)
body += chunk;
);
res.on("end", function()
let json = JSON.parse(body);
for (let i = 0; i < json.data.length; i++)
titles.push(json.data[i].Title);
// console.log(json);
resolve(
titles: titles,
page: page,
total_pages: json.total_pages
);
);
)
.on("error", function(e)
console.error("Got an error: ", e);
reject(e);
);
);
;
function getMovieTitles(substr)
const promises = [];
const titles = [];
getMovieTitlesData(substr).then(result =>
titles.push(...result.titles);
for (let i = result.page + 1; i <= result.total_pages; i++)
promises.push(getMovieTitlesData(substr, i));
Promise.all(promises).then(datas =>
datas.forEach(data =>
titles.push(...data.titles);
);
console.log(titles.sort());
);
);
getMovieTitles("spiderman");
【讨论】:
【参考方案4】:import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
/**
*
*
*/
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(Include.NON_NULL)
public class MovieTitle
@JsonProperty("Poster")
private String poster;
@JsonProperty("Title")
private String title;
@JsonProperty("Type")
private String type;
@JsonProperty("Year")
private String year;
@JsonProperty("imdbID")
private String imdbID;
public String getPoster()
return poster;
public void setPoster(String poster)
this.poster = poster;
public String getTitle()
return title;
public void setTitle(String title)
this.title = title;
public String getType()
return type;
public void setType(String type)
this.type = type;
public String getYear()
return year;
public void setYear(String year)
this.year = year;
public String getImdbID()
return imdbID;
public void setImdbID(String imdbID)
this.imdbID = imdbID;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
/**
* @author
*
*/
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(Include.NON_NULL)
public class SearchResult
@JsonProperty("page")
private String page;
@JsonProperty("per_page")
private String per_page;
@JsonProperty("total")
private String total;
@JsonProperty("total_pages")
private String total_pages;
@JsonProperty("data")
private List<MovieTitle> movieTitles;
public String getPage()
return page;
public void setPage(String page)
this.page = page;
public String getPer_page()
return per_page;
public void setPer_page(String per_page)
this.per_page = per_page;
public String getTotal()
return total;
public void setTotal(String total)
this.total = total;
public String getTotal_pages()
return total_pages;
public void setTotal_pages(String total_pages)
this.total_pages = total_pages;
public List<MovieTitle> getMovieTitles()
return movieTitles;
public void setMovieTitles(List<MovieTitle> movieTitles)
this.movieTitles = movieTitles;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Proxy.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import com.rest.model.SearchResult;
/**
* @author
*
*/
public class SprngRestClient
public static void main(String args[])
getMovieTitles("spiderman");
static void getMovieTitles(String movietitle)
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
Proxy proxy = new Proxy(Type.HTTP, new InetSocketAddress("sample.proxy", 8080));
requestFactory.setProxy(proxy);
List<String> moviewTitles = new ArrayList<String>();
RestTemplate restTemplate = new RestTemplate(requestFactory);
int pageNo = 0;
int totalPages = 100000;
while (pageNo != totalPages)
pageNo = pageNo + 1;
SearchResult quote = restTemplate.getForObject(
"https://jsonmock.hackerrank.com/api/movies/search/?Title=" + movietitle + "&page=" + pageNo,
SearchResult.class);
moviewTitles.addAll(quote.getMovieTitles()
.stream()
.map(title -> title.getTitle())
.collect(Collectors.toList()));
pageNo = Integer.parseInt(quote.getPage());
totalPages = Integer.parseInt(quote.getTotal_pages());
moviewTitles.sort((name1, name2) -> name1.compareTo(name2));
moviewTitles.forEach(System.out::println);
【讨论】:
【参考方案5】:import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
import java.net.*;
import com.google.gson.*;
public class Solution
static String[] getMovieTitles(String substr)
String response;
int startPage = 1;
int totalPages = Integer.MAX_VALUE;
List<String> titles = new ArrayList<>();
while (startPage <= totalPages)
try
URL obj = new URL(
"https://jsonmock.hackerrank.com/api/movies/search/?Title=" + substr + "&page=" + startPage);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
while ((response = in.readLine()) != null)
JsonObject convertedObject = new Gson().fromJson(response, JsonObject.class);
totalPages = convertedObject.get("total_pages").getAsInt();
JsonArray data = convertedObject.getAsJsonArray("data");
for (int i = 0; i < data.size(); i++)
String title = data.get(i).getAsJsonObject().get("Title").getAsString();
titles.add(title);
in.close();
startPage++;
catch (Exception ex)
ex.printStackTrace();
return null;
Collections.sort(titles);
return titles.toArray(new String[0]);
public static void main(String[] args) throws IOException
Scanner in = new Scanner(System.in);
final String fileName = System.getenv("OUTPUT_PATH");
BufferedWriter bw = new BufferedWriter(new FileWriter(fileName));
String[] res;
String _substr;
try
_substr = in.nextLine();
catch (Exception e)
_substr = null;
res = getMovieTitles(_substr);
for (int res_i = 0; res_i < res.length; res_i++)
bw.write(String.valueOf(res[res_i]));
bw.newLine();
bw.close();
【讨论】:
不鼓励仅使用代码回答。请添加一些解释,说明这是如何解决问题的,或者这与现有答案有何不同。 From Review【参考方案6】:如果有人在寻找 GET AUTHOR ARTICLES 问题,那么下面是我的 Python 解决方案
import requests
import json
def getArticleTitles(author):
# Write your code here
if not author: return []
titles = []
st, total = 1, float('inf')
while st <= total:
url = "https://jsonmock.hackerrank.com/api/articles?author=0&page=1".format(author, st)
response = requests.get(url)
res = json.loads(response.content)
total = res['total_pages']
for t in res['data']:
if not t['title'] and not t['story_title']:
continue
elif not t['title']:
titles += [t['story_title']]
else:
titles += [t['title']]
st += 1
return titles
【讨论】:
谢谢分享,完美运行:)【参考方案7】:你可以使用 java 8 Stream APi
private String[] getMovieTitlesFromApi(String query)
List<String> titlesLst = new ArrayList<>();
IntStream.iterate(1, n -> n + 1).takeWhile(n -> n < totalPages).limit(totalPages).forEach(c ->
try (BufferedReader reader = new BufferedReader(new InputStreamReader(
new URL("https://jsonmock.hackerrank.com/api/movies/search/?Title=" + URLEncoder.encode(query, "UTF-8") + "&page=" + c)
.openConnection().getInputStream())))
Supplier<Stream<String>> contentStream = reader::lines;
Optional<JsonObject> objectAsJob = contentStream.get()
.map(contentStreamLine -> new Gson().fromJson(contentStreamLine, JsonObject.class)).findFirst();
totalPages = objectAsJob.map(convertedLines -> convertedLines.get("total_pages").getAsInt()).get();
Optional<JsonArray> dataFilter = objectAsJob.map(convertedLines -> convertedLines.getAsJsonArray("data"));
IntStream.iterate(0, n -> n + 1).takeWhile(n -> n < dataFilter.get().size()).forEach(dataLines ->
titlesLst.add(dataFilter.get().get(dataLines).getAsJsonObject().get("Title").getAsString());
Collections.sort(titlesLst);
);
catch (Exception e)
e.printStackTrace();
totalPages++;
);
storeMovieTitlesInCache(query, titlesLst.stream().distinct().collect(Collectors.toList()).toArray(new String[0]));
return titlesLst.toArray(new String[0]);
【讨论】:
我看到他们不允许你使用 Gaon 库。 你对 Gson 的看法是吧?【参考方案8】:使用异步等待
const https = require('https');
// function returns a Promise
const getPromise = (movie_title, page = 1) =>
return new Promise((resolve, reject) =>
https.get(
`https://jsonmock.hackerrank.com/api/movies/search/?Title=$movie_title&page=$page`,
response =>
let chunks_of_data = [];
response.on('data', fragments =>
chunks_of_data.push(fragments);
);
response.on('end', () =>
let data = Buffer.concat(chunks_of_data);
resolve(JSON.parse(data));
);
response.on('error', error =>
reject(error);
);
);
);
;
// async function to make http request
const makeSynchronousRequest = async movie_title =>
try
// maing a req for number of pages
let http_promise = getPromise(movie_title);
let response_body = await http_promise;
let titles = [];
for (let page_num = 1; page_num <= response_body.total_pages; page_num++)
// maing a req for titles of movies
let http_promise = getPromise(movie_title, page_num);
let response_body = await http_promise;
// holds response from server that is passed when Promise is resolved
response_body.data.forEach(item =>
titles.push(item.Title);
);
console.log(titles.sort());
catch (error)
// Promise rejected
console.log(error);
;
function getMovieTitles(movie_title)
makeSynchronousRequest(movie_title);
getMovieTitles('batman');
【讨论】:
你是冠军。【参考方案9】:感谢 HackerRank 问题。它让我明白,我不应该过分依赖 Spring Boot 注解。
这是我无法回答的一个问题,显然我过于依赖使用 Spring Boot 注解no @JSONProperty, no @RequestBody, and walla I can't do much :)
。这是我面试后写的。我希望它很容易理解。
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
import java.net.*;
import com.google.gson.*;
class MovieTitle
String Title;
int Year;
String imdbID;
class JSONResponse
int page;
int per_page;
int total;
int total_pages;
List<MovieTitle> data;
public class Solution
/*
* Complete the function below.
*/
static String[] getMovieTitles(String substr)
List<String> titles = new ArrayList<String>();
int pageNumber = 1;
int total_pages = 1;
while (pageNumber <= total_pages)
try
System.out.println("https://jsonmock.hackerrank.com/api/movies/search/?Title=" + substr + "&pageNumber=" + pageNumber);
URL url = new URL("https://jsonmock.hackerrank.com/api/movies/search/?Title=" + substr + "&pageNumber=" + pageNumber);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
String response = null;
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
while ((response = bufferedReader.readLine()) != null)
Gson gson = new Gson();
JSONResponse json = gson.fromJson(response, JSONResponse.class);
total_pages = json.total_pages;
List<MovieTitle> data = json.data;
for (MovieTitle title : data)
titles.add(title.Title);
bufferedReader.close();
pageNumber++;
catch (MalformedURLException e)
e.printStackTrace();
catch (IOException e)
e.printStackTrace();
//complete function here
return titles.toArray(new String[0]);
public static void main(String[] args) throws IOException
Scanner in = new Scanner(System.in);
final String fileName = "file.txt";
BufferedWriter bw = new BufferedWriter(new FileWriter(fileName));
String[] res;
String _substr;
try
_substr = in.nextLine();
catch (Exception e)
_substr = null;
res = getMovieTitles(_substr);
for (int res_i = 0; res_i < res.length; res_i++)
bw.write(String.valueOf(res[res_i]));
bw.newLine();
bw.close();
【讨论】:
【参考方案10】:这是我在 python 中的解决方案:
import requests
import json
def getMovieTitles(substr):
titles = []
data = requests.get("https://jsonmock.hackerrank.com/api/movies/search/?Title=".format(substr))
response = json.loads(data.content.decode('utf-8'))
for page in range(0, response["total_pages"]):
page_response = requests.get("https://jsonmock.hackerrank.com/api/movies/search/?Title=&page=".format(substr, page + 1))
page_content = json.loads(page_response.content.decode('utf-8'))
#print ('page_content', page_content, 'type(page_content)', type(page_content))
for item in range(0, len(page_content["data"])):
titles.append(str(page_content["data"][item]["Title"]))
titles.sort()
return titles
print(getMovieTitles("spiderman"))
【讨论】:
【参考方案11】:这里是 a2441918 的相同代码,但改进了! 承诺更少的回调
这段代码是可测试的和模块化的 也是 ES6 风格
导入模块
const https = require('https');
网址应该是动态的(这可以改进)
const url = (title, pageNum = 1) => 'https://jsonmock.hackerrank.com/api/movies/search/?Title=' + title + "&page=" + pageNum
分离获取请求,这将允许编写一次并根据需要多次使用
function requestGET(url)
return new Promise((resolve, reject) =>
https.get(url, res =>
console.log(res.statusCode, res.statusCode >= 400)
if ( res.statusCode >= 200 && res.statusCode < 400 )
res.on('data', body =>
resolve(body)
)
if(res.statusCode >= 400)
// since it needs to parse the response
// in case of 400 sed back an empty object
// on this method alone can add huge improvement
// but that will be a huge waste of time,
// since great libraries are out there
reject(JSON.stringify())
).on('error', (e) =>
console.error(`Got error: $e.message`);
)
)
此方法将使代码更具可读性
const convertToString = arr =>
console.log(arr.join('\n'))
最后是结束通话:
function getMovieTitles(substr)
fetchData(substr);
const res = getMovieTitles('yfvuguoguogguoyguogouyg')
【讨论】:
以上是关于解决方案电影标题中缺少代码的片段,完成挑战更多[关闭]的主要内容,如果未能解决你的问题,请参考以下文章