Ready-to-Use Code
Browse and copy useful code snippets for algorithms, UI components, utilities, and more. Curated by MUITSA members.
Showing 13 snippets
C++ - Quick Sort Algorithm
Efficient sorting algorithm with O(n log n) average time complexity
#include <iostream>
using namespace std;
int partition(int arr[], int low, int high) {
int pivot = arr[high];
int i = low - 1;
for (int j = low; j < high; j++) {
if (arr[j] < pivot) {
i++;
swap(arr[i], arr[j]);
}
}
swap(arr[i + 1], arr[high]);
return i + 1;
}
void quickSort(int arr[], int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}C++ - Linked List Implementation
Basic linked list with insert and display operations
struct Node {
int data;
Node* next;
Node(int val) : data(val), next(nullptr) {}
};
class LinkedList {
private:
Node* head;
public:
LinkedList() : head(nullptr) {}
void insert(int val) {
Node* newNode = new Node(val);
if (!head) {
head = newNode;
return;
}
Node* temp = head;
while (temp->next) temp = temp->next;
temp->next = newNode;
}
void display() {
Node* temp = head;
while (temp) {
cout << temp->data << " -> ";
temp = temp->next;
}
cout << "NULL\n";
}
};Java - Object-Oriented Programming Basics
Encapsulation and basic OOP principles in Java
public class Student {
private String name;
private int studentId;
private double gpa;
// Constructor
public Student(String name, int id, double gpa) {
this.name = name;
this.studentId = id;
this.gpa = gpa;
}
// Getters
public String getName() { return name; }
public int getStudentId() { return studentId; }
public double getGPA() { return gpa; }
// Method to check if student is on dean's list
public boolean isDeansList() {
return gpa >= 3.5;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", id=" + studentId +
", gpa=" + gpa + '}';
}
}Java - ArrayList and Collections
Working with ArrayList and Stream API for data manipulation
import java.util.*;
public class StudentManager {
private List<Student> students = new ArrayList<>();
public void addStudent(Student student) {
students.add(student);
}
public List<Student> getDeansList() {
return students.stream()
.filter(Student::isDeansList)
.sorted(Comparator.comparingDouble(Student::getGPA).reversed())
.collect(Collectors.toList());
}
public void displayAllStudents() {
students.forEach(System.out::println);
}
public Student findById(int id) {
return students.stream()
.filter(s -> s.getStudentId() == id)
.findFirst()
.orElse(null);
}
}Machine Learning - Linear Regression
Predict continuous values using linear regression
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score
# Sample data: Study hours vs Exam scores
X = np.array([[2], [3], [4], [5], [6], [7], [8], [9]])
y = np.array([50, 55, 65, 70, 75, 85, 90, 95])
# Split data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
# Create and train the model
model = LinearRegression()
model.fit(X_train, y_train)
# Make predictions
y_pred = model.predict(X_test)
# Evaluate the model
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
print(f"Mean Squared Error: {mse:.2f}")
print(f"R² Score: {r2:.2f}")
print(f"Slope: {model.coef_[0]:.2f}")
print(f"Intercept: {model.intercept_:.2f}")Machine Learning - K-Means Clustering
Group similar data points using unsupervised learning
import numpy as np
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt
# Sample data: Student performance metrics
data = np.array([
[85, 90], [88, 92], [78, 80], [92, 95],
[45, 50], [48, 52], [42, 48], [50, 55],
[65, 70], [68, 72], [62, 68], [70, 75]
])
# Standardize the features
scaler = StandardScaler()
data_scaled = scaler.fit_transform(data)
# Apply K-Means clustering
kmeans = KMeans(n_clusters=3, random_state=42, n_init=10)
clusters = kmeans.fit_predict(data_scaled)
# Print cluster centers
print("Cluster Centers:")
for i, center in enumerate(kmeans.cluster_centers_):
print(f"Cluster {i}: {center}")
# Visualize clusters
plt.scatter(data[:, 0], data[:, 1], c=clusters, cmap='viridis')
plt.scatter(kmeans.cluster_centers_[:, 0],
kmeans.cluster_centers_[:, 1],
marker='X', s=200, c='red')
plt.xlabel('Math Score')
plt.ylabel('Science Score')
plt.title('Student Performance Clustering')
plt.show()Machine Learning - Neural Network Basics
Build and train a neural network for multi-class classification
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import numpy as np
# Create a simple neural network for classification
model = keras.Sequential([
layers.Dense(64, activation='relu', input_shape=(10,)),
layers.Dropout(0.2),
layers.Dense(32, activation='relu'),
layers.Dropout(0.2),
layers.Dense(16, activation='relu'),
layers.Dense(3, activation='softmax') # 3 classes
])
# Compile the model
model.compile(
optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy']
)
# Sample training data
X_train = np.random.randn(100, 10)
y_train = keras.utils.to_categorical(
np.random.randint(0, 3, 100), 3
)
# Train the model
history = model.fit(
X_train, y_train,
epochs=20,
batch_size=32,
validation_split=0.2,
verbose=1
)
# Make predictions
X_test = np.random.randn(10, 10)
predictions = model.predict(X_test)
print("Predictions shape:", predictions.shape)Debounce Function
Delay function execution until user stops triggering events
function debounce(func, delay) {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => func(...args), delay);
};
}React Custom Hook - useLocalStorage
Persist state to localStorage with React hooks
function useLocalStorage(key, initialValue) {
const [storedValue, setStoredValue] = useState(() => {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
console.error(error);
return initialValue;
}
});
const setValue = (value) => {
try {
setStoredValue(value);
window.localStorage.setItem(key, JSON.stringify(value));
} catch (error) {
console.error(error);
}
};
return [storedValue, setValue];
}Binary Search Algorithm
Efficient search algorithm for sorted arrays
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1Responsive Grid Layout
Auto-responsive grid that adapts to screen size
.grid-container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 1.5rem;
padding: 2rem;
}
@media (max-width: 768px) {
.grid-container {
grid-template-columns: 1fr;
gap: 1rem;
}
}SQL Query - Top N Records
Get top 10 students by GPA using window functions
SELECT
student_id,
name,
gpa,
ROW_NUMBER() OVER (ORDER BY gpa DESC) as rank
FROM students
WHERE gpa >= 3.5
LIMIT 10;Fetch API with Error Handling
Robust API call with proper error handling
async function fetchData(url) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error('Fetch error:', error);
throw error;
}
}C++ - Quick Sort Algorithm
Efficient sorting algorithm with O(n log n) average time complexity
#include <iostream>
using namespace std;
int partition(int arr[], int low, int high) {
int pivot = arr[high];
int i = low - 1;
for (int j = low; j < high; j++) {
if (arr[j] < pivot) {
i++;
swap(arr[i], arr[j]);
}
}
swap(arr[i + 1], arr[high]);
return i + 1;
}
void quickSort(int arr[], int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}C++ - Linked List Implementation
Basic linked list with insert and display operations
struct Node {
int data;
Node* next;
Node(int val) : data(val), next(nullptr) {}
};
class LinkedList {
private:
Node* head;
public:
LinkedList() : head(nullptr) {}
void insert(int val) {
Node* newNode = new Node(val);
if (!head) {
head = newNode;
return;
}
Node* temp = head;
while (temp->next) temp = temp->next;
temp->next = newNode;
}
void display() {
Node* temp = head;
while (temp) {
cout << temp->data << " -> ";
temp = temp->next;
}
cout << "NULL\n";
}
};Java - Object-Oriented Programming Basics
Encapsulation and basic OOP principles in Java
public class Student {
private String name;
private int studentId;
private double gpa;
// Constructor
public Student(String name, int id, double gpa) {
this.name = name;
this.studentId = id;
this.gpa = gpa;
}
// Getters
public String getName() { return name; }
public int getStudentId() { return studentId; }
public double getGPA() { return gpa; }
// Method to check if student is on dean's list
public boolean isDeansList() {
return gpa >= 3.5;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", id=" + studentId +
", gpa=" + gpa + '}';
}
}Java - ArrayList and Collections
Working with ArrayList and Stream API for data manipulation
import java.util.*;
public class StudentManager {
private List<Student> students = new ArrayList<>();
public void addStudent(Student student) {
students.add(student);
}
public List<Student> getDeansList() {
return students.stream()
.filter(Student::isDeansList)
.sorted(Comparator.comparingDouble(Student::getGPA).reversed())
.collect(Collectors.toList());
}
public void displayAllStudents() {
students.forEach(System.out::println);
}
public Student findById(int id) {
return students.stream()
.filter(s -> s.getStudentId() == id)
.findFirst()
.orElse(null);
}
}Machine Learning - Linear Regression
Predict continuous values using linear regression
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score
# Sample data: Study hours vs Exam scores
X = np.array([[2], [3], [4], [5], [6], [7], [8], [9]])
y = np.array([50, 55, 65, 70, 75, 85, 90, 95])
# Split data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
# Create and train the model
model = LinearRegression()
model.fit(X_train, y_train)
# Make predictions
y_pred = model.predict(X_test)
# Evaluate the model
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
print(f"Mean Squared Error: {mse:.2f}")
print(f"R² Score: {r2:.2f}")
print(f"Slope: {model.coef_[0]:.2f}")
print(f"Intercept: {model.intercept_:.2f}")Machine Learning - K-Means Clustering
Group similar data points using unsupervised learning
import numpy as np
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt
# Sample data: Student performance metrics
data = np.array([
[85, 90], [88, 92], [78, 80], [92, 95],
[45, 50], [48, 52], [42, 48], [50, 55],
[65, 70], [68, 72], [62, 68], [70, 75]
])
# Standardize the features
scaler = StandardScaler()
data_scaled = scaler.fit_transform(data)
# Apply K-Means clustering
kmeans = KMeans(n_clusters=3, random_state=42, n_init=10)
clusters = kmeans.fit_predict(data_scaled)
# Print cluster centers
print("Cluster Centers:")
for i, center in enumerate(kmeans.cluster_centers_):
print(f"Cluster {i}: {center}")
# Visualize clusters
plt.scatter(data[:, 0], data[:, 1], c=clusters, cmap='viridis')
plt.scatter(kmeans.cluster_centers_[:, 0],
kmeans.cluster_centers_[:, 1],
marker='X', s=200, c='red')
plt.xlabel('Math Score')
plt.ylabel('Science Score')
plt.title('Student Performance Clustering')
plt.show()Machine Learning - Neural Network Basics
Build and train a neural network for multi-class classification
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import numpy as np
# Create a simple neural network for classification
model = keras.Sequential([
layers.Dense(64, activation='relu', input_shape=(10,)),
layers.Dropout(0.2),
layers.Dense(32, activation='relu'),
layers.Dropout(0.2),
layers.Dense(16, activation='relu'),
layers.Dense(3, activation='softmax') # 3 classes
])
# Compile the model
model.compile(
optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy']
)
# Sample training data
X_train = np.random.randn(100, 10)
y_train = keras.utils.to_categorical(
np.random.randint(0, 3, 100), 3
)
# Train the model
history = model.fit(
X_train, y_train,
epochs=20,
batch_size=32,
validation_split=0.2,
verbose=1
)
# Make predictions
X_test = np.random.randn(10, 10)
predictions = model.predict(X_test)
print("Predictions shape:", predictions.shape)Debounce Function
Delay function execution until user stops triggering events
function debounce(func, delay) {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => func(...args), delay);
};
}React Custom Hook - useLocalStorage
Persist state to localStorage with React hooks
function useLocalStorage(key, initialValue) {
const [storedValue, setStoredValue] = useState(() => {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
console.error(error);
return initialValue;
}
});
const setValue = (value) => {
try {
setStoredValue(value);
window.localStorage.setItem(key, JSON.stringify(value));
} catch (error) {
console.error(error);
}
};
return [storedValue, setValue];
}Binary Search Algorithm
Efficient search algorithm for sorted arrays
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1Responsive Grid Layout
Auto-responsive grid that adapts to screen size
.grid-container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 1.5rem;
padding: 2rem;
}
@media (max-width: 768px) {
.grid-container {
grid-template-columns: 1fr;
gap: 1rem;
}
}SQL Query - Top N Records
Get top 10 students by GPA using window functions
SELECT
student_id,
name,
gpa,
ROW_NUMBER() OVER (ORDER BY gpa DESC) as rank
FROM students
WHERE gpa >= 3.5
LIMIT 10;Fetch API with Error Handling
Robust API call with proper error handling
async function fetchData(url) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error('Fetch error:', error);
throw error;
}
}Share Your Code Snippets
Have useful code snippets? Share them with the MUITSA community and help others solve problems faster.