How to sort List in dart based on value returned by a function - sorting

I have to show a list of stores in a sorted order by nearest location
and I have a unsorted list of stores and a function to calculate
distance of each store from my current location but I don't know how
to sort List in dart based on value returned by a function.
I am getting the unsorted List of stores data from an api.
I need logic for this question for sorting the _kikkleStores List
class KikkleStoresBloc extends BlocBase {
List<KikkleStoreInfo> _kikkleStores = [];
//for distance sorting
List<KikkleStoreInfo> _kikkleStoresSorted = [];
List<double> distanceFromCurrentLocation;//already got
value in it
bool hasReachedEndOfList = false;
Coordinate _currentLocation;
KikkleStoresBloc();
final _kikkleStoreSubject =
BehaviorSubject<List<KikkleStoreInfo>>
();
// Getter Stream
Stream<List<KikkleStoreInfo>> get kikkleStores =>
_kikkleStoreSubject.stream;`enter code here`
// Getter Sink
Function(List<KikkleStoreInfo>) get _fetchedkikkleStores =>
_kikkleStoreSubject.sink.add;
getKikkleStores() async {
try {
if (_currentPage <= _totalPages) {
final response = await
ApiController.getKikkleStores(_currentPage);
_kikkleStores.addAll(response.item1);
//here how to sort _kikkleStores by using
getStoreDistance function
_totalPages = response.item3;
_fetchedkikkleStores(_kikkleStores);
if (_currentPage == _totalPages) {
hasReachedEndOfList = true;
} else if (_currentPage < _totalPages &&
_kikkleStores.length
< 10) {
}
}
}
}
// this function returns distance
getStoreDistance(Coordinate currentLocation, KikkleStoreInfo
store)
async {
if (currentLocation == null) return 0.0;
try {
double distanceInMeter = await
LocationUtils.getDistanceInMeters(
currentLocation, Coordinate(store.latitude,
store.longitude));
// final miles = (distanceInMeter / 1609.344).round();
return distanceInMeter;
} catch (e) {
return 0.0;
}
}
void getCurrentLocation() async {
try {
final isAllowed = await
PermissionsUtils.isLocationAccessAllowed();
if (isAllowed) {
final coordinates = await
LocationUtils.getCurrentLocation();
if (coordinates != null) {
_currentLocation = coordinates;
}
}
}
catch (e) {
print(e);
}
}
}

Take the reference of below code
void main(){
List<POJO> pojo = [POJO(5), POJO(3),POJO(7),POJO(1)];
// fill list
pojo..sort((a, b) => a.id.compareTo(b.id));
for(var i in pojo){
print(i.id); // prints list in sorted order i.e 1 3 5 7
}
}
class POJO {
int id;
POJO(this.id);
}

void sortfun() async {
for (int c = 0; c < (_kikkleStores.length - 1); c++) {
for (int d = 0; d < _kikkleStores.length - c - 1; d++) {
if (await getStoreDistance(_currentLocation, _kikkleStores[d]) >
await getStoreDistance(_currentLocation,
_kikkleStores[d + 1])) /* For descending order use < */
{
swap = _kikkleStores[d];
_kikkleStores[d] = _kikkleStores[d + 1];
_kikkleStores[d + 1] = swap;
}
}
}
}

Related

Sorting League Standings table

Am doing a league management system where the system generates fixtures and assign each match to an official who later enters results. Now when i have set everything possible for the log table but when i pass the results, am getting the some few errors : Too few arguments to function App\Models\Gamescores::updateStandings(), 0 passed in E:\Video\laraVids\laraProjects\HAM\app\Models\Gamescores.php on line 28 and exactly 1 expected
here is my code for the sorting of the league
class Gamescores extends Model
{
use HasFactory;
protected $table = 'gamescores';
protected $fillable = [
'games_id',
'away_score',
'home_score',
];
public function game()
{
return $this->belongsTo(Game::class, 'games_id');
}
public static function boot()
{
parent::boot();
static::created(function ($gamescore) {
$gamescore->updateStandings();
});
}
public function updateStandings($league_id)
{
// Get all gamescores for the specified league
$gameScores = Gamescores::whereHas('game', function ($query) use ($league_id) {
$query->where('league_id', $league_id);
})->get();
// Loop through each gamescore and update the log table for each team
foreach ($gameScores as $gameScore) {
$game = Games::find($gameScore->games_id);
$league_id = $game->league_id;
$home_team_id = $game->home_team;
$away_team_id = $game->away_team;
$home_team_log = Logtable::where('team_id', $home_team_id)->first();
if ($home_team_log !== null) {
$home_team_log->played += 1;
if ($gameScore->home_score > $gameScore->away_score) {
$home_team_log->won += 1;
$home_team_log->points += 3;
} else if ($gameScore->home_score == $gameScore->away_score) {
$home_team_log->drawn += 1;
$home_team_log->points += 1;
} else {
$home_team_log->lost += 1;
}
$home_team_log->goals_for += $gameScore->home_score;
$home_team_log->goals_against += $gameScore->away_score;
$home_team_log->goal_difference = $home_team_log->goals_for - $home_team_log->goals_against;
$home_team_log->save();
}
$away_team_log = Logtable::where('team_id', $away_team_id)->first();
if ($away_team_log !== null) {
$away_team_log->played += 1;
if ($gameScore->away_score > $gameScore->home_score) {
$away_team_log->won += 1;
$away_team_log->points += 3;
} else if ($gameScore->home_score == $gameScore->away_score) {
$away_team_log->drawn += 1;
$away_team_log->points += 1;
} else {
$away_team_log->lost += 1;
}
$away_team_log->goals_for += $gameScore->away_score;
$away_team_log->goals_against += $gameScore->home_score;
$away_team_log->goal_difference = $away_team_log->goals_for - $away_team_log->goals_against;
$away_team_log->save();
}
}
}
}
thats my model where am passing the method to genererate the results
public function fixtureToView($league)
{
// Fetch all rows from the games table, including the related official model
$games = Games::where('league_id', $league)->get();
// Extract the values for the role column as an array
$pluckedFixtures = $games->pluck('Fixture')->toArray();
// Count the number of occurrences of each value in the array
$counts = array_count_values($pluckedFixtures);
// Initialize an empty array to store the duplicate keys and values
$fixtures = collect([]);
// Iterate over the counts array
foreach ($counts as $key => $count) {
// If the count is greater than 1, add the key and value to the duplicates array
$fixtures->push($games->where('Fixture', $key));
}
// In your controller
$gamescores = Gamescores::all();
foreach ($gamescores as $gamescore) {
$game = Games::find($gamescore->games_id);
$league_id = $game->league_id;
$gamescore->updateStandings($league_id);
if($gamescore->games_id){
$game = Games::find($gamescore->games_id);
$league_id = $game->league_id;
$gamescore->updateStandings($league_id);
}
}
$standings = Logtable::all();
$standings = $standings->sortByDesc('points');
// return view('standings', compact('standings'));
return view(
'admin.league.fixtures.index',
compact('fixtures', 'standings')
);
thats my controller where am passing the method to retrieve it in the view, what i want is the log table to get the Id of the league where the games/matches belong to
the error am getting this error

Why is my result variable not being changed?

So I am trying to solve N-Queens problem, and when I console.log(result) inside the solve function I am getting the correct output. but when I return the result array in the end, it seems like the result array has not been mutated at all, as I get [[-, -, -,-], [-,-,-,-]]
function solveNQueens(n) {
let result = [];
let buffer = Array(n).fill('-');
function solve(bufferIndexRow) {
if (bufferIndexRow === n) {
result.push(buffer);
return console.log('FOUND ONE SOLUTION'); // Finished last row, filled queens array
}
for (let column = 0; column < n; column++) {
buffer[bufferIndexRow] = column;
if (isValid(bufferIndexRow, column)) {
solve(bufferIndexRow + 1);
}
buffer[bufferIndexRow] = '-'
}
}
function isValid(row, col) {
for(let i = 0; i< row; i++) {
if(buffer[i] == col || Math.abs(i - row) == Math.abs(buffer[i]- col))
return false;
}
return true;
}
solve(0);
return result;
}
console.log(solveNQueens(4));
you need to pass in buffer to solve so that it can push the updated buffer to result

Spring GCP - Datastore performance: Batch processing, iteration through all entity list is very slow

Following code is work really slow, almost 30 second to process 400 entities:
int page = 0;
org.springframework.data.domain.Page<MyEntity> slice = null;
while (true) {
if (slice == null) {
slice = repo.findAll(PageRequest.of(page, 400, Sort.by("date")));
} else {
slice = repo.findAll(slice.nextPageable());
}
if (!slice.hasNext()) {
break;
}
slice.getContent().forEach(v -> v.setApp(SApplication.NAME_XXX));
repo.saveAll(slice.getContent());
LOGGER.info("processed: " + page);
page++;
}
I use following instead, 4-6 sec per 400 entities (gcp lib to work with datastore)
Datastore service = DatastoreOptions.getDefaultInstance().getService();
StructuredQuery.Builder<?> query = Query.newEntityQueryBuilder();
int limit = 400;
query.setKind("ENTITY_KIND").setLimit(limit);
int count = 0;
Cursor cursor = null;
while (true) {
if (cursor != null) {
query.setStartCursor(cursor);
}
QueryResults<?> queryResult = service.run(query.build());
List<Entity> entityList = new ArrayList<>();
while (queryResult.hasNext()) {
Entity loadEntity = (Entity) queryResult.next();
Entity.Builder newEntity = Entity.newBuilder(loadEntity).set("app", SApplication.NAME_XXX.name());
entityList.add(newEntity.build());
}
service.put(entityList.toArray(new Entity[0]));
count += entityList.size();
if (entityList.size() == limit) {
cursor = queryResult.getCursorAfter();
} else {
break;
}
LOGGER.info("Processed: {}", count);
}
Why I can't use spring to do that batch processing?
Full discussion here: https://github.com/spring-cloud/spring-cloud-gcp/issues/1824
First:
you need to use correct lib version: at least 1.2.0.M2
Second:
you need to implement new method in repository interface:
#Query("select * from your_kind")
Slice<TestEntity> findAllSlice(Pageable pageable);
Final code looks like:
LOGGER.info("start");
int page = 0;
Slice<TestEntity> slice = null;
while (true) {
if (slice == null) {
slice = repo.findAllSlice(DatastorePageable.of(page, 400, Sort.by("date")));
} else {
slice = repo.findAllSlice(slice.nextPageable());
}
if (!slice.hasNext()) {
break;
}
slice.getContent().forEach(v -> v.setApp("xx"));
repo.saveAll(slice.getContent());
LOGGER.info("processed: " + page);
page++;
}
LOGGER.info("end");

How to create all possible variations from single string presented in special format?

Let's say, I have following template.
Hello, {I'm|he is} a {notable|famous} person.
Result should be
Hello, I'm a notable person.
Hello, I'm a famous person.
Hello, he is a notable person.
Hello, he is a famous person.
The only possible solution I have in mind - full search, but it is not effective.
May be there is a good algorithm for such kind of job but I do not know what task about. All permutations in array is very close to this but I have no idea how to use it here.
Here is working solution (it's part of object, so here is only relevant part).
generateText() parses string and converts 'Hello, {1|2}, here {3,4}' into ['Hello', ['1', '2'], 'here', ['3', '4']]]
extractText() takes this multidimensional array and creates all possible strings
STATE_TEXT: 'TEXT',
STATE_INSIDE_BRACKETS: 'INSIDE_BRACKETS',
generateText: function(text) {
var result = [];
var state = this.STATE_TEXT;
var length = text.length;
var simpleText = '';
var options = [];
var singleOption = '';
var i = 0;
while (i < length) {
var symbol = text[i];
switch(symbol) {
case '{':
if (state === this.STATE_TEXT) {
simpleText = simpleText.trim();
if (simpleText.length) {
result.push(simpleText);
simpleText = '';
}
state = this.STATE_INSIDE_BRACKETS;
}
break;
case '}':
if (state === this.STATE_INSIDE_BRACKETS) {
singleOption = singleOption.trim();
if (singleOption.length) {
options.push(singleOption);
singleOption = '';
}
if (options.length) {
result.push(options);
options = [];
}
state = this.STATE_TEXT;
}
break;
case '|':
if (state === this.STATE_INSIDE_BRACKETS) {
singleOption = singleOption.trim();
if (singleOption.length) {
options.push(singleOption);
singleOption = '';
}
}
break;
default:
if (state === this.STATE_TEXT) {
simpleText += symbol;
} else if (state === this.STATE_INSIDE_BRACKETS) {
singleOption += symbol;
}
break;
}
i++;
}
return result;
},
extractStrings(generated) {
var lengths = {};
var currents = {};
var permutations = 0;
var length = generated.length;
for (var i = 0; i < length; i++) {
if ($.isArray(generated[i])) {
lengths[i] = generated[i].length;
currents[i] = lengths[i];
permutations += lengths[i];
}
}
var strings = [];
for (var i = 0; i < permutations; i++) {
var string = [];
for (var k = 0; k < length; k++) {
if (typeof lengths[k] === 'undefined') {
string.push(generated[k]);
continue;
}
currents[k] -= 1;
if (currents[k] < 0) {
currents[k] = lengths[k] - 1;
}
string.push(generated[k][currents[k]]);
}
strings.push(string.join(' '));
}
return strings;
},
The only possible solution I have in mind - full search, but it is not effective.
If you must provide full results, you must run full search. There is simply no way around it. You don't need all permutations, though: the number of results is equal to the product of the number of alternatives in each template.
Although there are multiple ways to implement this, recursion is among the most popular approaches. Here is some pseudo-code to get you started:
string[][] templates = {{"I'm", "he is"}, {"notable", "famous", "boring"}}
int[] pos = new int[templates.Length]
string[] fills = new string[templates.Length]
recurse(templates, fills, 0)
...
void recurse(string[][] templates, string[] fills, int pos) {
if (pos == fills.Length) {
formatResult(fills);
} else {
foreach option in templates[pos] {
fills[pos] = option
recurse(templates, fills, pos+1);
}
}
}
It seems like the best solution here is going to be n*m where n=the first array and m= the second array . There are nm required lines of output, which means that as long as you are only doing nm you aren't doing any extra work
The generic running time for this is where there is more than 2 arrays with options, it would be
n1*n2...*nm where each of those is equal to the size of the respective list
A nested loop where you just print out the value for the current index of the outer loop along with the current value for the index of the inner loop should do this properly

How to correct loop counters for maze algorithm?

I have figured out how to move my character around the maze using the algorithm I have written, but the count is not figuring correctly. At the end of each row my character moves up and down several times until the count reaches the specified number to exit the loop, then the character moves along the next row down until it reaches the other side and repeats the moving up and down until the count reaches the specified number again. Can anyone help me find why my count keeps getting off? The algorithm and the maze class I am calling from is listed below.
public class P4 {
public static void main(String[] args) {
// Create maze
String fileName = args[3];
Maze maze = new Maze(fileName);
System.out.println("Maze name: " + fileName);
// Get dimensions
int mazeWidth = maze.getWidth();
int mazeHeight = maze.getHeight();
// Print maze size
System.out.println("Maze width: " + mazeWidth);
System.out.println("Maze height: " + mazeHeight);
int r = 0;
int c = 0;
// Move commands
while (true){
for (c = 0; c <= mazeWidth; c++){
if (maze.moveRight()){
maze.isDone();
c++;
}
if (maze.isDone() == true){
System.exit(1);
}
if (maze.moveRight() == false && c != mazeWidth){
maze.moveDown();
maze.moveRight();
maze.moveRight();
maze.moveUp();
c++;
}
}
for (r = 0; r % 2 == 0; r++){
maze.moveDown();
maze.isDone();
if (maze.isDone() == true){
System.exit(1);
}
}
for (c = mazeWidth; c >= 0; c--){
if (maze.moveLeft()){
c--;
maze.isDone();
System.out.println(c);
}
if (maze.isDone() == true){
System.exit(1);
}
if (maze.moveLeft() == false && c != 0){
maze.moveDown();
maze.moveLeft();
maze.moveLeft();
maze.moveUp();
c--;
}
}
for (r = 1; r % 2 != 0; r++){
maze.moveDown();
maze.isDone();
if (maze.isDone() == true){
System.exit(1);
}
}
}
}
}
public class Maze {
// Maze variables
private char mazeData[][];
private int mazeHeight, mazeWidth;
private int finalRow, finalCol;
int currRow;
private int currCol;
private int prevRow = -1;
private int prevCol = -1;
// User interface
private JFrame frame;
private JPanel panel;
private Image java, student, success, donotpass;
private ArrayList<JButton> buttons;
// Maze constructor
public Maze(String fileName) {
// Read maze
readMaze(fileName);
// Graphics setup
setupGraphics();
}
// Get height
public int getHeight() {
return mazeHeight;
}
// Get width
public int getWidth() {
return mazeWidth;
}
// Move right
public boolean moveRight() {
// Legal move?
if (currCol + 1 < mazeWidth) {
// Do not pass?
if (mazeData[currRow][currCol + 1] != 'D')
{
currCol++;
redraw(true);
return true;
}
}
return false;
}
// Move left
public boolean moveLeft() {
// Legal move?
if (currCol - 1 >= 0) {
// Do not pass?
if (mazeData[currRow][currCol - 1] != 'D')
{
currCol--;
redraw(true);
return true;
}
}
return false;
}
// Move up
public boolean moveUp() {
// Legal move?
if (currRow - 1 >= 0) {
// Do not pass?
if (mazeData[currRow - 1][currCol] != 'D')
{
currRow--;
redraw(true);
return true;
}
}
return false;
}
// Move down
public boolean moveDown() {
// Legal move?
if (currRow + 1 < mazeHeight) {
// Do not pass?
if (mazeData[currRow + 1][currCol] != 'D')
{
currRow++;
redraw(true);
return true;
}
}
return false;
}
public boolean isDone() {
// Maze solved?
if ((currRow == finalRow) && (currCol == finalCol))
return true;
else
return false;
}
private void redraw(boolean print) {
// Wait for awhile
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
if (print)
System.out.println("Moved to row " + currRow + ", column " + currCol);
// Compute index and remove icon
int index = (prevRow * mazeWidth) + prevCol;
if ((prevRow >= 0) && (prevCol >= 0)) {
buttons.get(index).setIcon(null);
}
// Compute index and add icon
index = (currRow * mazeWidth) + currCol;
if ((currRow == finalRow) && (currCol == finalCol))
buttons.get(index).setIcon(new ImageIcon(success));
else
buttons.get(index).setIcon(new ImageIcon(student));
// Store previous location
prevRow = currRow;
prevCol = currCol;
}
// Set button
private void setButton(JButton button, int row, int col) {
if (mazeData[row][col] == 'S') {
button.setIcon(new ImageIcon(student));
currRow = row;
currCol = col;
} else if (mazeData[row][col] == 'J') {
button.setIcon(new ImageIcon(java));
finalRow = row;
finalCol = col;
} else if (mazeData[row][col] == 'D') {
button.setIcon(new ImageIcon(donotpass));
}
}
// Read maze
private void readMaze(String filename) {
try {
// Open file
Scanner scan = new Scanner(new File(filename));
// Read numbers
mazeHeight = scan.nextInt();
mazeWidth = scan.nextInt();
// Allocate maze
mazeData = new char[mazeHeight][mazeWidth];
// Read maze
for (int row = 0; row < mazeHeight; row++) {
// Read line
String line = scan.next();
for (int col = 0; col < mazeWidth; col++) {
mazeData[row][col] = line.charAt(col);
}
}
// Close file
scan.close();
} catch (IOException e) {
System.out.println("Cannot read maze: " + filename);
System.exit(0);
}
}
// Setup graphics
private void setupGraphics() {
// Create grid
frame = new JFrame();
panel = new JPanel();
panel.setLayout(new GridLayout(mazeHeight, mazeWidth, 0, 0));
frame.add(Box.createRigidArea(new Dimension(0, 5)), BorderLayout.NORTH);
frame.add(panel, BorderLayout.CENTER);
// Look and feel
try {
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
// Configure window
frame.setSize(mazeWidth * 100, mazeHeight * 100);
frame.setTitle("Maze");
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setAlwaysOnTop(true);
// Load and scale images
ImageIcon icon0 = new ImageIcon("Java.jpg");
Image image0 = icon0.getImage();
java = image0.getScaledInstance(100, 100, Image.SCALE_DEFAULT);
ImageIcon icon1 = new ImageIcon("Student.jpg");
Image image1 = icon1.getImage();
student = image1.getScaledInstance(100, 100, Image.SCALE_DEFAULT);
ImageIcon icon2 = new ImageIcon("Success.jpg");
Image image2 = icon2.getImage();
success = image2.getScaledInstance(100, 100, Image.SCALE_DEFAULT);
ImageIcon icon3 = new ImageIcon("DoNotPass.jpg");
Image image3 = icon3.getImage();
donotpass = image3.getScaledInstance(100, 100, Image.SCALE_DEFAULT);
// Build panel of buttons
buttons = new ArrayList<JButton>();
for (int row = 0; row < mazeHeight; row++) {
for (int col = 0; col < mazeWidth; col++) {
// Initialize and add button
JButton button = new JButton();
Border border = new LineBorder(Color.darkGray, 4);
button.setOpaque(true);
button.setBackground(Color.gray);
button.setBorder(border);
setButton(button, row, col);
panel.add(button);
buttons.add(button);
}
}
// Show window
redraw(false);
frame.setVisible(true);
}
}
One error I can see in your code is that you're incrementing your c counter more often than you should. You start with it managed by your for loop, which means that it will be incremented (or decremented, for the leftward moving version) at the end of each pass through the loop. However, you also increment it an additional time in two of your if statements. That means that c might increase by two or three on a single pass through the loop, which is probably not what you intend.
Furthermore, the count doesn't necessarily have anything obvious to do with the number of moves you make. The loop code will always increase it by one, even if you're repeatedly trying to move through an impassible wall.
I don't really understand what your algorithm is supposed to be, so I don't have any detailed advice for how to fix your code.
One suggestion I have though is that you probably don't ever want to be calling methods on your Maze class without paying attention to their return values. You have a bunch of places where you call isDone but ignore the return value, which doesn't make any sense. Similarly, you should always be checking the return values from your moveX calls, to see if the move was successful or not. Otherwise you may just blunder around a bunch, without your code having any clue where you are in the maze.

Resources