Skip to content

Instantly share code, notes, and snippets.

func linearSearch(slice []int, target int) (index, numTests int) {
for idx, val := range slice {
if val == target {
return idx, idx + 1
}
}
return -1, len(slice)
}
@rphuber
rphuber / counting_sort.go
Created April 13, 2024 12:36
Implemtation of counting sort in go
func countingSort(slice []Customer) []Customer {
// slice `sortedSlice` is created to store the sorted values
sortedSlice := make([]Customer, len(slice))
// slice `countSlice` is created to store the count of each value (line 32).
countSlice := make([]int, len(slice))
// `countSlice` is populated by iterating over the input `slice` and incrementing the count of each `Customer`'s `numPurchases`
for _, customer := range slice {
countSlice[customer.numPurchases]++
}
package main
import (
"fmt"
"math/rand"
)
func main() {
// Get the number of items and maximum item value.
var numItems, max int
func bubbleSort(slice []int) {
n := len(slice)
for {
swapped := false
for i := 1; i < n; i++ {
if slice[i-1] > slice[i] {
slice[i-1], slice[i] = slice[i], slice[i-1]
swapped = true
}
}
use std::time::Instant;
// the board dimensions
const NUM_ROWS: usize = 6;
const NUM_COLS: usize = NUM_ROWS;
fn main() {
// create a new board with all entries set to UNVISITED
let mut board = [[','; NUM_COLS]; NUM_ROWS];
use std::time::Instant;
// The board dimensions
const NUM_ROWS: usize = 8;
const NUM_COLS: usize = NUM_ROWS;
const INUM_ROWS: isize = NUM_ROWS as isize;
const INUM_COLS: isize = NUM_COLS as isize;
// Whether we want an open or closed tour
const REQUIRE_CLOSED_TOUR: bool = false;
use std::io;
use std::io::Write;
fn main() {
// create a vector to hold the fibonacci values and prefill with 0, 1
println!("Enter -1 to exit");
let mut fill_on_the_fly = vec![0, 1];
loop {
let n = get_isize("Enter a number: ");
if n == -1 {
use std::io;
fn main() {
println!("Enter -1 to exit");
loop {
let n = get_isize("Enter a number: ");
if n == -1 {
break;
}
println!("fibonacci of {} is {}", n, fibonacci(n));
fn main() {
for n in 0..22 {
println!("{}! = {}", n, factorial(n));
}
}
fn factorial(n: isize) -> isize {
// base case
if n == 0 {
1
func CountBits(x int) int {
numBits := 0
for x != 0 {
numBits += x & 1
x >>= 1
}
return numBits
}