Skip to content

Instantly share code, notes, and snippets.

@jwalsh
Last active January 20, 2023 22:49
Show Gist options
  • Save jwalsh/fa6ee638230f39e2c6c2d54d811400ee to your computer and use it in GitHub Desktop.
Save jwalsh/fa6ee638230f39e2c6c2d54d811400ee to your computer and use it in GitHub Desktop.

Scratchpad

append

Implement append in Scheme, TypeScript, Python, and Kotlin

Here is an implementation of the append function in Scheme:

(define (append lst1 lst2)
  (if (null? lst1)
      lst2
      (cons (car lst1) (append (cdr lst1) lst2))))

Here is an implementation of the append function in TypeScript:

function append(list1: any[], list2: any[]): any[] {
    return list1.concat(list2);
}

Here is an implementation of the append function in Python:

def append(lst1, lst2):
    return lst1 + lst2

Here is an implementation of the append function in Kotlin:

fun append(list1: List<Any>, list2: List<Any>): List<Any> {
    return list1 + list2
}

It is worth noting that in the Python and Kotlin implementations, the + operator is used to concatenate the two input lists, while in Scheme and TypeScript the built-in concatenation function is used.

most-popular

Implement most-popular that takes a list of items like [1, 2, 1, 3, 5, 7, 9, 5, 5] and an argument like the number to return like 2 and gives back [5, 1] in Scheme, Python, TypeScript, Kotlin, and Clojure

Here is an implementation of the most-popular function in Scheme:

(define (most-popular lst n)
  (let ((counter (make-hash-table)))
    (for-each (lambda (x) (hash-table-update! counter x add1 0)) lst)
    (let ((sorted-items (sort (hash-table->list counter) (lambda (a b) (> (cdr a) (cdr b))))))
      (let loop ((n n) (sorted-items sorted-items) (result '()))
        (if (or (zero? n) (null? sorted-items))
            result
            (loop (- n 1) (cdr sorted-items) (cons (car (car sorted-items)) result))))))

Here is an implementation of the most-popular function in Python:

from collections import Counter

def most_popular(lst, n):
    counter = Counter(lst)
    return [item[0] for item in counter.most_common(n)]

Here is an implementation of the most-popular function in TypeScript:

function mostPopular(lst: any[], n: number): any[] {
    const counter = new Map<any, number>();
    for (const item of lst) {
        if (counter.has(item)) {
            counter.set(item, counter.get(item) + 1);
        } else {
            counter.set(item, 1);
        }
    }
    return Array.from(counter.entries())
        .sort((a, b) => b[1] - a[1])
        .slice(0, n)
        .map((item) => item[0]);
}

Here is an implementation of the most-popular function in Kotlin:

fun mostPopular(lst: List<Any>, n: Int): List<Any> {
    val counter = mutableMapOf<Any, Int>()
    for (item in lst) {
        val count = counter.getOrDefault(item, 0)
        counter[item] = count + 1
    }
    return counter.toList()
        .sortedByDescending { (_, value) -> value }
        .take(n)
        .map { it.first }
}

Here is an implementation of the most-popular function in Clojure:

(defn most-popular [lst n]
  (let [counter (frequencies lst)]
    (->> (sort-by val > counter)
         (take n)
         (map key))))

Please note that in the TypeScript implementation I used Map and in the Kotlin one I used a MutableMap to count the items. In the Python implementation, I used the collections.Counter library, in the Scheme implementation I used the built-in make-hash-table and in the clojure one I used frequencies function to count items.

gcd

Implement (gcd n) in Scheme, Python, TypeScript, Kotlin, and Clojure

Here is an implementation of the gcd function in Scheme:

(define (gcd n)
  (define (iter m r)
    (if (= r 0)
        m
        (iter r (modulo m r))))
  (iter n (modulo n (sub1 n))))

Here is an implementation of the gcd function in Python:

def gcd(n: int) -> int:
    while n != 0:
        n, m = m % n, n
    return m

Here is an implementation of the gcd function in TypeScript:

function gcd(n: number): number {
    let m = n - 1;
    while (m !== 0) {
        [n, m] = [m, n % m];
    }
    return n;
}

Here is an implementation of the gcd function in Kotlin:

fun gcd(n: Int): Int {
    var m = n - 1
    while (m != 0) {
        val temp = m
        m = n % m
        n = temp
    }
    return n
}

Here is an implementation of the gcd function in Clojure:

(defn gcd [n]
  (loop [m (dec n) r (mod n (dec n))]
    (if (zero? r)
      m
      (recur r (mod m r)))))

Please note that in the Scheme and Python implementation, the built-in modulo and % operator are used to find the remainder of the division between two numbers and in the TypeScript, Kotlin and Clojure implementation the modulo operator % is used to find the remainder of the division. Also, note that the gcd function uses the Euclidean algorithm to compute the greatest common divisor.

const esprima = require('esprima');
const code = `
function add(a, b) {
return a + b;
}
console.log(add(1, 2));
`;
const ast = esprima.parseScript(code);
console.log(ast);
import com.amazonaws.services.ec2.AmazonEC2
import com.amazonaws.services.ec2.model.Instance
import com.amazonaws.services.ec2.model.Tag
class AwsResourceAuditor(private val ec2Client: AmazonEC2) {
fun checkUnusedEc2Instances(): List<Instance> {
val allInstances = ec2Client.describeInstances().reservations.flatMap { it.instances }
return allInstances.filter {
it.state.name == "running" && it.tags.none { tag -> tag.key == "Keep" }
}
}
}
#!/bin/bash
# Declare an array of top-level directories
declare -a top_dirs=("coding-exercises" "data-structures" "algorithms" "oop" "languages" "engineering" "web-development" "databases" "operating-systems" "networks" "security")
# Declare an array of subdirectories for the data structures directory
declare -a data_structures_dirs=("arrays" "linked-lists" "stacks" "queues" "trees" "heaps" "graphs")
# Declare an array of subdirectories for the algorithms directory
declare -a algorithms_dirs=("sorting" "searching" "traversal" "recursion" "dynamic-programming")
# Create the top-level directories
for dir in "${top_dirs[@]}"; do
mkdir "$dir"
done
# Change into the data structures directory
cd data-structures
# Create the data structures subdirectories
for dir in "${data_structures_dirs[@]}"; do
mkdir "$dir"
done
# Change back to the top-level directory
cd ..
# Change into the algorithms directory
cd algorithms
# Create the algorithms subdirectories
for dir in "${algorithms_dirs[@]}"; do
mkdir "$dir"
done
# Change back to the top-level directory
cd ..
#!/bin/bash
output_file=''
show_description=false
show_info=false
install_aws=false
install_kubernetes=false
install_java=false
install_python=false
install_node=false
install_go=false
generate_markdown () {
tool_name=$1
description=$2
info_url=$3
echo "## $tool_name"
echo "$description"
echo ""
echo "For more information, visit: $info_url"
}
install_or_show_version () {
tool_name=$1
description=$2
info_url=$3
installation_command=$4
if ! command -v "$tool_name" &> /dev/null; then
echo "$tool_name is not installed. Installing..."
eval "$installation_command"
fi
if [ "$show_description" = true ] || [ "$show_info" = true ]; then
generate_markdown "$tool_name" "$description" "$info_url" >> $output_file
else
echo "## $tool_name"
$tool_name --version
echo ""
fi
}
while getopts "adi:jknp:m:s" opt; do
case $opt in
a)
install_aws=true
;;
d)
show_description=true
;;
i)
show_info=true
output_file=$OPTARG
;;
j)
install_java=true
;;
k)
install_kubernetes=true
;;
n)
install_node=true
;;
p)
install_python=true
;;
s)
install_go=true
;;
\?)
echo "Invalid option: -$OPTARG" >&2
exit 1
;;
esac
done
# Set default output file name if not provided
if [ "$show_info" = true ] && [ -z "$output_file" ]; then
output_file="tool_info.md"
fi
install_or_show_version "Brew" \
"Brew is a package manager for macOS." \
"https://brew.sh" \
'/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"'
install_or_show_version "Git" \
"Git is a version control system for tracking changes in source code during software development." \
"https://git-scm.com" \
'brew install git'
from typing import List, Dict
def resolve_orders(game: 'Game', orders: Dict[str, List[Order]]) -> None:
# Iterate over the orders for each player
for player, player_orders in orders.items():
# Iterate over each order for the player
for order in player_orders:
# Check the type of the order
if order.action == "move":
# If the order is a move order, check if the unit's current location is in the allowed_movements list
if order.unit.location in order.unit.allowed_movements:
# If the unit is allowed to move, update the unit's location and remove it from the original territory
order.target.units.append(order.unit)
order.unit.location.units.remove(order.unit)
order.unit.location = order.target
# Update the allowed_movements list for the unit based on its new location
order.unit.allowed_movements = order.unit.get_allowed_movements()
else:
# If the unit is not allowed to move, print an error message
print(f"Error: {order.unit} cannot move to {order.target}")
elif order.action == "support":
# If the order is a support order, check if the unit's current location is in the allowed_movements list
if order.unit.location in order.unit.allowed_movements:
# If the unit is allowed to support, add the support to the target territory's supports list
order.target.supports.append(order.unit)
else:
# If the unit is not allowed to support, print an error message
print(f"Error: {order.unit} cannot support {order.target}")
elif order.action == "convoy":
# If the order is a convoy order, check if the unit is a fleet and the target territory is reachable via convoy
if isinstance(order.unit, Fleet) and order.target.is_reachable_via_convoy():
# If the conditions are met, update the target territory's units list to include the unit being convoyed
order.target.units.append(order.target.convoyed_unit)
# Remove the unit being convoyed from its original territory
order.target.convoyed_unit.location.units.remove(order.target.convoyed_unit)
# Update the location of the unit being convoyed to the target territory
order.target.convoyed_unit.location = order.target
# Clear the convoyed_unit attribute of the target territory
order.target.convoyed_unit = None
else:
# If the unit is not a fleet or the target territory is not reachable via convoy, print an error message
print(f"Error: {order.unit} cannot convoy {order.target}")
elif order.action == "hold":
# If the order is a hold order, do nothing
pass
import pygame
# Initialize Pygame
pygame.init()
# Set the window size
window_size = (400, 600)
# Create the window
screen = pygame.display.set_mode(window_size)
# Set the title of the window
pygame.display.set_caption("Virtual Keyboard")
# Set the font for the keys
font = pygame.font.Font(None, 32)
# Set the dimensions for the keys
key_width = window_size[0] // 10
key_height = window_size[1] // 10
# Create a list of keys
keys = [
"1", "2", "3", "4", "5", "6", "7", "8", "9", "0",
"q", "w", "e", "r", "t", "y", "u", "i", "o", "p",
"a", "s", "d", "f", "g", "h", "j", "k", "l",
"z", "x", "c", "v", "b", "n", "m",
"space", "backspace"
]
# Set the colors for the keys
colors = {
"white": (255, 255, 255),
"gray": (128, 128, 128),
"black": (0, 0, 0)
}
# Set the initial position for the keys
x = 0
y = 0
# Create a dictionary of key objects
key_objects = {}
# Create the keys
for key in keys:
# Create the key object
key_object = pygame.Rect(x, y, key_width, key_height)
# Add the key object to the dictionary
key_objects[key] = key_object
# Increment the x position for the next key
x += key_width
# If we have reached the end of a row, set x back to 0 and increment y
if x >= window_size[0]:
x = 0
y += key_height
# Set the initial text to an empty string
text = ""
# Set the running variable to True
running = True
# Run the game loop
while running:
# Fill the screen with black
screen.fill(colors["black"])
# Draw the keys
for key, key_object in key_objects.items():
# Set the text for the key
key_text = font.render(key, True, colors["white"])
# Get the text dimensions
key_text_dimensions = key_text.get_size()
# Calculate the position for the text
key_text_x = key_object.x + (key_width - key_text_dimensions[0]) // 2
key_text_y = key_object.y + (key_height - key_text_dimensions[1]) // 2
# Draw the text on the screen
screen.blit(key_text, (key_text_x, key_text_y))
# Draw a rectangle around the text
pygame.draw.rect(screen, colors["gray
import random
class Player:
def __init__(self, name):
self.name = name
self.position = 0
self.money = 1500
self.properties = []
self.in_jail = False
def take_turn(self, dice_roll):
if self.in_jail:
self.in_jail = False
print(f"{self.name} is out of jail")
else:
self.position += dice_roll
if self.position >= len(board):
self.position -= len(board)
print(f"{self.name} moved to {board[self.position]}")
def buy_property(self, tile):
if self.money >= tile.cost:
self.money -= tile.cost
self.properties.append(tile)
tile.owner = self.name
print(f"{self.name} bought {tile.name} for {tile.cost}")
else:
print(f"{self.name} can't afford {tile.name}")
def mortgage_property(self, tile):
self.money += tile.cost / 2
tile.owner = None
self.properties.remove(tile)
print(f"{self.name} mortgaged {tile.name} for {tile.cost / 2}")
def unmortgage_property(self, tile):
if self.money >= tile.cost / 2:
self.money -= tile.cost / 2
self.properties.append(tile)
tile.owner = self.name
print(f"{self.name} unmortgaged {tile.name} for {tile.cost / 2}")
else:
print(f"{self.name} can't afford to unmortgage {tile.name}")
def go_to_jail(self):
self.position = 10
self.in_jail = True
print(f"{self.name} went to jail")
board = [
Tile("GO", 0),
Tile("A1", 60),
Tile("CC1", 0),
Tile("A2", 60),
Tile("T1", 0),
Tile("R1", 200),
Tile("B1", 100),
Tile("CH1", 0),
Tile("B2", 100),
Tile("B3", 120),
Tile("JAIL", 0),
# ...
]
player1 = Player("player1")
player2 = Player("player2")
for round in range(100):
dice_roll = random.randint(1, 6) + random.randint(1, 6)
player1.take_turn(dice_roll)
if board[player1.position].cost > 0 and board[player1.position].owner is None:
player1.buy_property(board[player1.position])
dice_roll
openapi: 3.0.0
info:
title: My API
version: 1.0.0
servers:
- url: https://api.example.com/v1
description: Production server
- url: http://localhost:8000
description: Development server
paths:
/users:
get:
summary: Get a list of users
operationId: listUsers
tags:
- users
parameters:
- in: query
name: limit
required: false
schema:
type: integer
minimum: 1
maximum: 100
responses:
'200':
description: A list of users
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/User'
components:
schemas:
User:
type: object
required:
- id
- name
properties:
id:
type: integer
format: int64
name:
type: string
email:
type: string
format: email
components:
schemas:
SNSMessage:
type: object
required:
- Type
- MessageId
- TopicArn
- Message
- Timestamp
- SignatureVersion
- Signature
- SigningCertURL
properties:
Type:
type: string
MessageId:
type: string
TopicArn:
type: string
Message:
Require Import List.
Fixpoint sorted (l : list nat) : Prop :=
match l with
| nil => True
| x :: nil => True
| x :: y :: l' => (x <= y) /\ sorted (y :: l')
end.
Theorem sort_correct : forall l : list nat, sorted (sort l).
Proof.
(* Proof goes here *)
Qed.
fun getTopSellers(sales: List<Sale>): List<Product> {
// Create a map where the key is the product and the value is the number of times it was sold
val salesCount = mutableMapOf<Product, Int>()
for (sale in sales) {
val product = sale.product
val count = salesCount.getOrDefault(product, 0)
salesCount[product] = count + 1
}
// Sort the map by value in descending order and return the list of products
return salesCount.toList().sortedByDescending { (_, value) -> value }.map { (key, _) -> key }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment