oppgaver så langt

This commit is contained in:
Håkon Størdal 2025-03-22 13:49:25 +01:00
parent 4f3385850f
commit df84d4f18e
17 changed files with 628 additions and 0 deletions

6
add-binary-67/Cargo.toml Normal file
View file

@ -0,0 +1,6 @@
[package]
name = "add-binary-67"
version = "0.1.0"
edition = "2024"
[dependencies]

66
add-binary-67/src/main.rs Normal file
View file

@ -0,0 +1,66 @@
struct Solution {}
impl Solution {
pub fn add_binary(a: String, b: String) -> String {
let mut result = String::new();
let mut carry = 0;
// Convert strings to character vectors and reverse them for easier processing
let a_chars: Vec<char> = a.chars().rev().collect();
let b_chars: Vec<char> = b.chars().rev().collect();
// Get the maximum length of the two strings
let max_len = std::cmp::max(a_chars.len(), b_chars.len());
// Perform binary addition digit by digit
for i in 0..max_len {
// Get digits at current position or 0 if we've reached the end
let a_digit = if i < a_chars.len() {
a_chars[i].to_digit(2).unwrap()
} else {
0
};
let b_digit = if i < b_chars.len() {
b_chars[i].to_digit(2).unwrap()
} else {
0
};
// Calculate sum and new carry
let sum = a_digit + b_digit + carry;
carry = sum / 2;
let digit = sum % 2;
// Add the current digit to the result
result.push(char::from_digit(digit, 2).unwrap());
}
// Don't forget the final carry if it exists
if carry > 0 {
result.push('1');
}
// Reverse the result and return
result.chars().rev().collect()
}
// pub fn add_binary(a: String, b: String) -> String {
// let num1 = u128::from_str_radix(a.as_str(), 2).expect("Valid binary string");
// let num2 = u128::from_str_radix(b.as_str(), 2).expect("Valid binary string");
// let sum = num1 + num2;
// let binary_sum = format!("{:b}", sum); // format as binary string
// println!("Sum in decimal: {}", sum);
// println!("Sum in binary: {}", binary_sum);
// binary_sum
// }
}
fn main() {
let a: String = "111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111".to_string();
let b: String = "11010100101110111000111".to_string();
println!("{:?}", Solution::add_binary(a, b));
}

View file

@ -0,0 +1,6 @@
[package]
name = "binary-tree-inorder-traversal-94"
version = "0.1.0"
edition = "2024"
[dependencies]

View file

@ -0,0 +1,75 @@
// Definition for a binary tree node.
#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
pub val: i32,
pub left: Option<Rc<RefCell<TreeNode>>>,
pub right: Option<Rc<RefCell<TreeNode>>>,
}
impl TreeNode {
#[inline]
pub fn new(val: i32) -> Self {
TreeNode {
val,
left: None,
right: None,
}
}
}
use std::cell::RefCell;
use std::rc::Rc;
pub fn inorder_traversal_recursively(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
let mut result = Vec::new();
helper(&root, &mut result);
result
}
fn helper(node: &Option<Rc<RefCell<TreeNode>>>, result: &mut Vec<i32>) {
if let Some(n) = node {
let n = n.borrow();
helper(&n.left, result); // Left subtree
result.push(n.val); // Current node
helper(&n.right, result); // Right subtree
}
}
pub fn inorder_traversal(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
let mut result = Vec::new();
let mut stack = Vec::new();
let mut current = root;
while current.is_some() || !stack.is_empty() {
while let Some(node) = current {
stack.push(node.clone());
current = node.borrow().left.clone();
}
if let Some(node) = stack.pop() {
let node = node.borrow();
result.push(node.val); // Visit current node
current = node.right.clone();
}
}
result
}
fn main() {
let values = vec![
Some(1),
Some(2),
Some(3),
Some(4),
Some(5),
None,
Some(8),
None,
None,
Some(6),
Some(7),
Some(9),
];
println!("{:?}", values);
}

View file

@ -0,0 +1,6 @@
[package]
name = "climbing-stairs-70"
version = "0.1.0"
edition = "2024"
[dependencies]

View file

@ -0,0 +1,37 @@
fn climb_stairs_on2(n: i32) -> i32 {
if n == 1 {
return 1;
}
if n == 2 {
return 2;
}
let sol = climb_stairs(n - 2) + climb_stairs(n - 1);
sol
}
fn climb_stairs(n: i32) -> i32 {
if n == 1 {
return 1;
}
if n == 2 {
return 2;
}
let mut prev = 1;
let mut curr = 2;
for _ in 3..=n {
let next = prev + curr;
prev = curr;
curr = next;
}
curr
}
fn main() {
println!("{}", climb_stairs(4));
}

View file

@ -0,0 +1,6 @@
[package]
name = "merge-sorted-array-88"
version = "0.1.0"
edition = "2024"
[dependencies]

View file

@ -0,0 +1,83 @@
pub fn merge_hacky(nums1: &mut Vec<i32>, m: i32, nums2: &mut Vec<i32>, n: i32) {
if n == 0 {
return;
}
if m == 0 {
*nums1 = nums2.clone();
return;
}
let mut num1_counter = (m - 1) as usize;
let mut num2_counter = (n - 1) as usize;
let while_bool = true;
// Iterate nums1 from len - n (which is 3) backwards
while while_bool {
let num1 = nums1[num1_counter];
let num2 = nums2[num2_counter];
if num1 < num2 {
nums1[num1_counter + num2_counter + 1] = num2;
if num2_counter == 0 {
break;
}
num2_counter -= 1;
} else if num1 > num2 {
nums1[num1_counter + num2_counter + 1] = num1;
if num1_counter == 0 {
nums1[..num2_counter + 1].copy_from_slice(&nums2[..num2_counter + 1]);
break;
}
num1_counter -= 1
} else {
nums1[num1_counter + num2_counter] = num2;
nums1[num1_counter + num2_counter + 1] = num1;
if num2_counter == 0 {
break;
}
num2_counter -= 1;
if num1_counter == 0 {
nums1[..num2_counter + 1].copy_from_slice(&nums2[..num2_counter + 1]);
break;
}
num1_counter -= 1
}
}
}
pub fn merge(nums1: &mut Vec<i32>, m: i32, nums2: &mut Vec<i32>, n: i32) {
let mut i = (m - 1) as usize;
let mut j = (n - 1) as usize;
let mut k = (m + n - 1) as usize;
while let Some(_) = nums1.get(k) {
if j == usize::MAX {
return;
}
if i == usize::MAX {
nums1[..=j].copy_from_slice(&nums2[..=j]);
return;
}
if nums1[i] < nums2[j] {
nums1[k] = nums2[j];
j = j.wrapping_sub(1);
} else {
nums1[k] = nums1[i];
i = i.wrapping_sub(1);
}
k = k.wrapping_sub(1);
}
}
fn main() {
let mut nums1 = vec![2, 0];
let m = 1;
let mut nums2 = vec![1];
let n = 1;
println!("{:?}", merge(&mut nums1, m, &mut nums2, n));
println!("{:?}", nums1)
}

6
plus-one-66/Cargo.toml Normal file
View file

@ -0,0 +1,6 @@
[package]
name = "plus-one-66"
version = "0.1.0"
edition = "2024"
[dependencies]

21
plus-one-66/src/main.rs Normal file
View file

@ -0,0 +1,21 @@
struct Solution {}
impl Solution {
pub fn plus_one(mut digits: Vec<i32>) -> Vec<i32> {
for val in digits.iter_mut().rev() {
if *val == 9 {
*val = 0;
} else {
*val += 1;
return digits;
}
}
digits.insert(0, 1);
digits
}
}
fn main() {
let digits = vec![9, 9, 8];
println!("{:#?}", Solution::plus_one(digits));
}

View file

@ -0,0 +1,6 @@
[package]
name = "remove-duplicates-from-sorted-list-83"
version = "0.1.0"
edition = "2024"
[dependencies]

View file

@ -0,0 +1,51 @@
// Definition for singly-linked list.
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct ListNode {
pub val: i32,
pub next: Option<Box<ListNode>>,
}
impl ListNode {
#[inline]
fn new(val: i32) -> Self {
ListNode { next: None, val }
}
}
pub fn to_linked_list(values: &[i32]) -> Option<Box<ListNode>> {
let mut head = None;
let mut current = &mut head;
for &val in values {
*current = Some(Box::new(ListNode::new(val)));
current = &mut current.as_mut().unwrap().next;
}
head
}
pub fn delete_duplicates(mut head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
let mut current = head.as_mut();
while let Some(node) = current {
while let Some(next) = node.next.as_mut() {
// Mutably borrow next
if node.val == next.val {
node.next = next.next.take(); // Take ownership of the next node safely
} else {
break;
}
}
current = node.next.as_mut(); // Move to the next distinct node
}
head
}
fn main() {
let values = [1, 2, 3, 3, 4];
let head = to_linked_list(&values);
println!("{:?}", head);
println!("{:?}", delete_duplicates(head));
}

View file

@ -0,0 +1,6 @@
[package]
name = "remove_duplicates"
version = "0.1.0"
edition = "2024"
[dependencies]

6
same-tree-100/Cargo.toml Normal file
View file

@ -0,0 +1,6 @@
[package]
name = "same-tree-100"
version = "0.1.0"
edition = "2024"
[dependencies]

181
same-tree-100/src/main.rs Normal file
View file

@ -0,0 +1,181 @@
// Definition for a binary tree node.
#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
pub val: i32,
pub left: Option<Rc<RefCell<TreeNode>>>,
pub right: Option<Rc<RefCell<TreeNode>>>,
}
impl TreeNode {
#[inline]
pub fn new(val: i32) -> Self {
TreeNode {
val,
left: None,
right: None,
}
}
}
struct Solution {}
use std::cell::RefCell;
use std::rc::Rc;
impl Solution {
pub fn is_same_tree(
p: Option<Rc<RefCell<TreeNode>>>,
q: Option<Rc<RefCell<TreeNode>>>,
) -> bool {
// Base cases: if either is None
match (p, q) {
// Both are None - trees are identical (empty)
(None, None) => true,
// One is None but the other isn't - trees are different
(Some(_), None) | (None, Some(_)) => false,
// Both trees have nodes - compare them recursively
(Some(p_node), Some(q_node)) => {
let p_borrow = p_node.borrow();
let q_borrow = q_node.borrow();
// Trees are the same if:
// 1. Current nodes have the same value
// 2. Left subtrees are the same
// 3. Right subtrees are the same
p_borrow.val == q_borrow.val
&& Solution::is_same_tree(p_borrow.left.clone(), q_borrow.left.clone())
&& Solution::is_same_tree(p_borrow.right.clone(), q_borrow.right.clone())
}
}
}
}
pub fn is_same_tree_iterativly(p: Option<Rc<RefCell<TreeNode>>>, q: Option<Rc<RefCell<TreeNode>>>) -> bool {
// Create a stack to store pairs of nodes to compare
let mut stack = Vec::new();
// Push the root pair to the stack
stack.push((p, q));
// Process nodes until the stack is empty
while !stack.is_empty() {
if let Some((p_opt, q_opt)) = stack.pop() {
match (p_opt, q_opt) {
// Both nodes are None, continue checking other pairs
(None, None) => continue,
// One node is None while the other isn't - trees differ
(Some(_), None) | (None, Some(_)) => return false,
// Both nodes exist, compare them
(Some(p_node), Some(q_node)) => {
let p_borrow = p_node.borrow();
let q_borrow = q_node.borrow();
// If values are different, trees differ
if p_borrow.val != q_borrow.val {
return false;
}
// Push right children to stack
stack.push((
p_borrow.right.clone(),
q_borrow.right.clone()
));
// Push left children to stack
stack.push((
p_borrow.left.clone(),
q_borrow.left.clone()
));
}
}
}
}
// If we've processed all nodes without finding differences, trees are identical
true
}
// Helper function to create trees from arrays
fn create_tree_from_vec(nums: &[Option<i32>], index: usize) -> Option<Rc<RefCell<TreeNode>>> {
if index >= nums.len() || nums[index].is_none() {
return None;
}
let val = nums[index].unwrap();
let mut node = TreeNode::new(val);
// Create left child (2*index + 1)
node.left = create_tree_from_vec(nums, 2 * index + 1);
// Create right child (2*index + 2)
node.right = create_tree_from_vec(nums, 2 * index + 2);
Some(Rc::new(RefCell::new(node)))
}
fn main() {
// Test case 1: Two identical trees
// 1
// / \
// 2 3
let tree1_data = vec![Some(1), Some(2), Some(3)];
let tree1 = create_tree_from_vec(&tree1_data, 0);
let tree2 = create_tree_from_vec(&tree1_data, 0);
// Expected: true
println!("Test case 1: {}", is_same_tree_iterativly(tree1, tree2));
// Test case 2: Different values in nodes
// 1 1
// / \ / \
// 2 3 2 4
let tree3_data = vec![Some(1), Some(2), Some(3)];
let tree4_data = vec![Some(1), Some(2), Some(4)];
let tree3 = create_tree_from_vec(&tree3_data, 0);
let tree4 = create_tree_from_vec(&tree4_data, 0);
// Expected: false
println!("Test case 2: {}", Solution::is_same_tree(tree3, tree4));
// Test case 3: Different structure
// 1 1
// / \ \
// 2 3 3
let tree5_data = vec![Some(1), Some(2), Some(3)];
let tree6_data = vec![Some(1), None, Some(3)];
let tree5 = create_tree_from_vec(&tree5_data, 0);
let tree6 = create_tree_from_vec(&tree6_data, 0);
// Expected: false
println!("Test case 3: {}", Solution::is_same_tree(tree5, tree6));
// Test case 4: Empty trees
let tree7: Option<Rc<RefCell<TreeNode>>> = None;
let tree8: Option<Rc<RefCell<TreeNode>>> = None;
// Expected: true
println!("Test case 4: {}", Solution::is_same_tree(tree7, tree8));
// Test case 5: One empty, one not
let tree9_data = vec![Some(1)];
let tree9 = create_tree_from_vec(&tree9_data, 0);
let tree10: Option<Rc<RefCell<TreeNode>>> = None;
// Expected: false
println!("Test case 5: {}", Solution::is_same_tree(tree9, tree10));
// Test case 6: More complex identical trees
// 1
// / \
// 2 3
// / \
// 4 5
let tree11_data = vec![Some(1), Some(2), Some(3), Some(4), None, None, Some(5)];
let tree11 = create_tree_from_vec(&tree11_data, 0);
let tree12 = create_tree_from_vec(&tree11_data, 0);
// Expected: true
println!("Test case 6: {}", Solution::is_same_tree(tree11, tree12));
}

6
sqrtx-69/Cargo.toml Normal file
View file

@ -0,0 +1,6 @@
[package]
name = "sqrtx-69"
version = "0.1.0"
edition = "2024"
[dependencies]

60
sqrtx-69/src/main.rs Normal file
View file

@ -0,0 +1,60 @@
// fn my_sqrt(x: i32) -> i32 {
// let mut upper_range = x / 2;
// let mut last_i = 0;
// if x <= 5 {
// upper_range = x;
// }
// if x >= i32::MAX {
// return (i32::MAX as f64).sqrt().floor() as i32;
// }
// for i in 0..=upper_range {
// let power_of_2 = i * i;
// if power_of_2 == x {
// return i;
// } else if power_of_2 > x {
// return last_i;
// } else {
// last_i = i;
// }
// }
// 0
// }
fn my_sqrt(x: i32) -> i32 {
if x < 2 {
return x; // Early return for 0 and 1
}
let mut right = 46340.min(x / 2);
if x >= right * right {
return right;
}
let mut left = 2;
while left <= right {
let mid = left + (right - left) / 2;
let mid_squared = mid * mid;
if mid_squared == x {
return mid;
} else if mid_squared < x {
left = mid + 1;
} else {
right = mid - 1;
}
}
right // After the loop, `right` is the largest value whose square is <= x}
}
fn main() {
// let sol = my_sqrt(2147483647);
let sol = my_sqrt(2147395599);
println!("{}", sol);
}