【发布时间】:2016-10-15 09:09:14
【问题描述】:
我为用户选择的每个类别提供两个随机视频。
我有一个用户偏好的字符串数组列表。
我还有一个包含数据库中所有视频的 ArrayList。
所以我尝试逐个搜索这些类别偏好,并找到两个适合这些类别的随机视频。
我已经实现了一个可行的解决方案(在一个小数据集上)。但考虑到很快会有 500 个视频、50 个类别并且用户将能够选择 5 个类别偏好,我不确定这是不是最佳方法:
我是这样解决的:
//Create a new array to store the videos
ArrayList<Video> videos = new ArrayList<>();
// Create counter for the position in the user preference array
int userPrefernceArrayIndex = 0;
// Create counter for number of successful category guesses
int numberOfSuccessfulGuesses = 0;
// Keep running until we have 2 videos for each of the user preferences
while (videos.size() < MainActivity.userPrefrencesStaticArraylist.size() * 2){
// Generate a random integer to get an entry random integer from the database array
Random rand = new Random();
int randomAlarmVidInt = rand.nextInt(MainActivity.allVideosFromDatabaseStaticArray.size());
// Find the category of the random video that was chosen
String categoryForRandomGuess = MainActivity.allVideosFromDatabaseStaticArray.get(randomAlarmVidInt).getVideoCategory();
// Find the current user video category we are testing for
String currentCategoryPreference = MainActivity.userPrefrencesStaticArraylist.get(userPrefernceArrayIndex);
// Check if category of the random video we got is the same as the category user
// preference we are testing for
if (categoryForRandomGuess.equals(currentCategoryPreference)){
// If it the the preference and the random video categories match add it to the video array
videos.add(MainActivity.allVideosFromDatabaseStaticArray.get(randomAlarmVidInt));
numberOfSuccessfulGuesses++;
// If the number of successful guesses is divisible by two then we have added two correct videos
// for that category so iterate to the next category
if (numberOfSuccessfulGuesses % 2 == 0){
userPrefernceArrayIndex++;
}
}
由于可能出现问题,除非必要,否则我几乎从不使用 while 循环或随机循环。我还看到猜测数字可能不是最好的解决方案记忆。所以我只是想确保我以最好的方式避免问题。
感谢您的帮助
【问题讨论】:
-
对于 500 个视频和 5 个类别偏好,我希望它可以正常工作。在任何情况下,智者都会说,在您知道自己遇到性能问题之前不要尝试优化。
-
很公平。谢谢
-
@NicholasMuir 如有任何疑问,请随意