Last active
June 2, 2023 13:40
-
-
Save bwnyasse/f75b844a00a0d0307a89ca770b4eae86 to your computer and use it in GitHub Desktop.
Code Patterns Flutter / Dart
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
import 'dart:math'; | |
void main() => runApp(const MyApp()); | |
class MyApp extends StatelessWidget { | |
const MyApp({Key? key}) : super(key: key); | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
title: 'Design Pattern Demo', | |
debugShowCheckedModeBanner: false, | |
theme: ThemeData( | |
primarySwatch: Colors.blue, | |
), | |
home: const SlidingWindowScreen(), | |
); | |
} | |
} | |
class SlidingWindowScreen extends StatefulWidget { | |
const SlidingWindowScreen({Key? key}) : super(key: key); | |
@override | |
SlidingWindowScreenState createState() => SlidingWindowScreenState(); | |
} | |
class SlidingWindowScreenState extends State<SlidingWindowScreen> | |
with SingleTickerProviderStateMixin { | |
List<int> numbers = []; | |
final int k = 3; | |
late AnimationController _animationController; | |
late Animation<Offset> _animation; | |
List<int> maxSumElements = []; | |
@override | |
void initState() { | |
super.initState(); | |
generateNumbers(); | |
_animationController = AnimationController( | |
vsync: this, | |
duration: const Duration(milliseconds: 500), | |
); | |
_animation = Tween<Offset>(begin: Offset.zero, end: const Offset(0.0, 1.0)) | |
.animate(_animationController); | |
} | |
@override | |
void dispose() { | |
_animationController.dispose(); | |
super.dispose(); | |
} | |
void generateNumbers() { | |
final random = Random(); | |
numbers = List.generate(10, (_) => random.nextInt(10)); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar( | |
title: const Text('Sliding Window - bwnyasse.net'), | |
), | |
body: Center( | |
child: Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: [ | |
const Text( | |
'Numbers:', | |
style: TextStyle(fontSize: 18), | |
), | |
const SizedBox(height: 10), | |
buildNumberList(), | |
const SizedBox(height: 20), | |
SlideTransition( | |
position: _animation, | |
child: Text( | |
'Max Sum of $k Consecutive Elements: ${findMaxSum()}', | |
style: | |
const TextStyle(fontSize: 24, fontWeight: FontWeight.bold), | |
), | |
), | |
], | |
), | |
), | |
floatingActionButton: FloatingActionButton( | |
onPressed: () { | |
setState(() { | |
generateNumbers(); | |
maxSumElements.clear(); | |
}); | |
}, | |
child: const Icon(Icons.play_arrow), | |
), | |
); | |
} | |
Widget buildNumberList() { | |
return SizedBox( | |
height: 40, | |
child: ListView.builder( | |
shrinkWrap: true, | |
scrollDirection: Axis.horizontal, | |
itemCount: numbers.length, | |
itemBuilder: (BuildContext context, int index) { | |
final color = | |
maxSumElements.contains(index) ? Colors.green : Colors.blue; | |
return Container( | |
width: 40, | |
height: 40, | |
margin: const EdgeInsets.symmetric(horizontal: 4), | |
decoration: BoxDecoration( | |
color: color, | |
borderRadius: BorderRadius.circular(8), | |
), | |
child: Center( | |
child: Text( | |
numbers[index].toString(), | |
style: const TextStyle(color: Colors.white), | |
), | |
), | |
); | |
}, | |
), | |
); | |
} | |
int findMaxSum() { | |
int maxSum = 0; | |
int currentSum = 0; | |
int maxSumIndex = 0; | |
// Calculate sum of first 'k' elements | |
for (int i = 0; i < k; i++) { | |
currentSum += numbers[i]; | |
} | |
maxSum = currentSum; | |
// Slide the window by one element at a time | |
for (int i = k; i < numbers.length; i++) { | |
currentSum = currentSum - numbers[i - k] + numbers[i]; | |
if (currentSum > maxSum) { | |
maxSum = currentSum; | |
maxSumIndex = i - k + 1; | |
} | |
} | |
maxSumElements = List<int>.generate(k, (index) => maxSumIndex + index); | |
return maxSum; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
import 'dart:math'; | |
void main() => runApp(MyApp()); | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
title: 'Flutter Demo', | |
debugShowCheckedModeBanner: false, | |
theme: ThemeData( | |
primarySwatch: Colors.blue, | |
), | |
home: IslandsScreen(), | |
); | |
} | |
} | |
class IslandsScreen extends StatefulWidget { | |
@override | |
_IslandsScreenState createState() => _IslandsScreenState(); | |
} | |
class _IslandsScreenState extends State<IslandsScreen> { | |
List<List<int>> grid = []; | |
int numIslands = 0; | |
@override | |
void initState() { | |
super.initState(); | |
generateGrid(); | |
countIslands(); | |
} | |
void generateGrid() { | |
final random = Random(); | |
final numRows = 3; | |
final numCols = 3; | |
grid = List.generate( | |
numRows, (_) => List.generate(numCols, (_) => random.nextInt(2))); | |
} | |
void countIslands() { | |
numIslands = 0; | |
if (grid.isEmpty) { | |
return; | |
} | |
final int rows = grid.length; | |
final int cols = grid[0].length; | |
final List<List<bool>> visited = List.generate( | |
rows, | |
(_) => List<bool>.filled(cols, false), | |
); | |
for (int i = 0; i < rows; i++) { | |
for (int j = 0; j < cols; j++) { | |
if (grid[i][j] == 1 && !visited[i][j]) { | |
numIslands++; | |
dfs(i, j, visited); | |
} | |
} | |
} | |
} | |
void dfs(int row, int col, List<List<bool>> visited) { | |
final int rows = grid.length; | |
final int cols = grid[0].length; | |
if (row < 0 || | |
row >= rows || | |
col < 0 || | |
col >= cols || | |
grid[row][col] == 0 || | |
visited[row][col]) { | |
return; | |
} | |
visited[row][col] = true; | |
// Explore neighbors in all four directions | |
dfs(row - 1, col, visited); // Up | |
dfs(row + 1, col, visited); // Down | |
dfs(row, col - 1, visited); // Left | |
dfs(row, col + 1, visited); // Right | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar( | |
title: Text('Islands'), | |
), | |
body: Center( | |
child: Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: [ | |
Text( | |
'Number of Islands: $numIslands', | |
style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold), | |
), | |
SizedBox(height: 20), | |
GridView.builder( | |
shrinkWrap: true, | |
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( | |
crossAxisCount: grid[0].length, | |
mainAxisSpacing: 4, | |
crossAxisSpacing: 4, | |
), | |
itemCount: grid.length * grid[0].length, | |
itemBuilder: (BuildContext context, int index) { | |
final int row = index ~/ grid[0].length; | |
final int col = index % grid[0].length; | |
final int value = grid[row][col]; | |
return Container( | |
color: value == 1 ? Colors.blue : Colors.white, | |
child: Center( | |
child: Text( | |
value.toString(), | |
style: TextStyle( | |
color: value == 1 ? Colors.white : Colors.black, | |
fontWeight: FontWeight.bold, | |
), | |
), | |
), | |
); | |
}, | |
), | |
], | |
), | |
), | |
floatingActionButton: FloatingActionButton( | |
onPressed: () { | |
setState(() { | |
generateGrid(); | |
countIslands(); | |
}); | |
}, | |
child: Icon(Icons.refresh), | |
), | |
); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file | |
// for details. All rights reserved. Use of this source code is governed by a | |
// BSD-style license that can be found in the LICENSE file. | |
import 'package:flutter/material.dart'; | |
import 'dart:math'; | |
void main() => runApp(MyApp()); | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
title: 'Flutter Demo', | |
debugShowCheckedModeBanner: false, | |
theme: ThemeData( | |
primarySwatch: Colors.blue, | |
), | |
home: TwoPointersScreen(), | |
); | |
} | |
} | |
class TwoPointersScreen extends StatefulWidget { | |
@override | |
_TwoPointersScreenState createState() => _TwoPointersScreenState(); | |
} | |
class _TwoPointersScreenState extends State<TwoPointersScreen> { | |
List<int> numbers = []; | |
int target = 0; | |
bool isPairFound = false; | |
int leftPointer = -1; | |
int rightPointer = -1; | |
@override | |
void initState() { | |
super.initState(); | |
generateInput(); | |
findPair(); | |
} | |
void generateInput() { | |
final random = Random(); | |
final numSet = Set<int>(); | |
while (numSet.length < 10) { | |
numSet.add(random.nextInt(30)); | |
} | |
numbers = numSet.toList(); | |
target = random.nextInt(70); | |
} | |
void findPair() { | |
isPairFound = false; | |
leftPointer = -1; | |
rightPointer = -1; | |
int left = 0; | |
int right = numbers.length - 1; | |
numbers.sort(); // Sorting the numbers to use the Two Pointers pattern | |
while (left < right) { | |
final int sum = numbers[left] + numbers[right]; | |
if (sum == target) { | |
isPairFound = true; | |
leftPointer = left; | |
rightPointer = right; | |
break; | |
} else if (sum < target) { | |
left++; | |
} else { | |
right--; | |
} | |
} | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar( | |
title: Text('Two Pointers'), | |
), | |
body: Center( | |
child: Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: [ | |
Text( | |
'Numbers:', | |
style: TextStyle(fontSize: 18), | |
), | |
SizedBox(height: 10), | |
buildNumberList(), | |
SizedBox(height: 10), | |
Text( | |
'Target: $target', | |
style: TextStyle(fontSize: 18), | |
), | |
SizedBox(height: 20), | |
Text( | |
'Pair Found: ${isPairFound ? "Yes" : "No"}', | |
style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold), | |
), | |
], | |
), | |
), | |
floatingActionButton: FloatingActionButton( | |
onPressed: () { | |
setState(() { | |
generateInput(); | |
findPair(); | |
}); | |
}, | |
child: Icon(Icons.refresh), | |
), | |
); | |
} | |
Widget buildNumberList() { | |
return Wrap( | |
spacing: 4, | |
runSpacing: 4, | |
children: numbers.map((number) { | |
final isHighlighted = | |
(numbers[leftPointer] == number || numbers[rightPointer] == number); | |
final color = isHighlighted ? Colors.green : Colors.blue; | |
return Container( | |
width: 40, | |
height: 40, | |
decoration: BoxDecoration( | |
color: color, | |
borderRadius: BorderRadius.circular(8), | |
), | |
child: Center( | |
child: Text( | |
number.toString(), | |
style: TextStyle(color: Colors.white), | |
), | |
), | |
); | |
}).toList(), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment