Giter Club home page Giter Club logo

Comments (22)

1ethanhansen avatar 1ethanhansen commented on August 16, 2024 1

Unfortunately I don't have the bandwidth to help with this at the moment. Cool initiative though! Hope the community can help :)

from vlang.

ErikSchierboom avatar ErikSchierboom commented on August 16, 2024

Exercise: hello-world

Code

module main

fn hello() string {
	return "Hello, World!"
}

Tags:

construct:module
construct:return
construct:string
construct:function
construct:invocation
construct:method
construct:return
construct:string
construct:unreachable-code
construct:visibility-modifiers
paradigm:functional
paradigm:object-oriented

from vlang.

ErikSchierboom avatar ErikSchierboom commented on August 16, 2024

Exercise: reverse-string

Code

module main

// reverse_string returns a given string in reverse order
fn reverse_string(str string) string {
    return str.split('').reverse().join('')
}

Tags:

construct:char
construct:comment
construct:function
construct:invocation
construct:method
construct:module
construct:parameter
construct:return
construct:string
construct:throw
construct:visibility-modifiers
paradigm:functional
paradigm:imperative
paradigm:object-oriented
technique:exceptions
technique:higher-order-functions

from vlang.

ErikSchierboom avatar ErikSchierboom commented on August 16, 2024

Exercise: triangle

Code

module main

fn is_equilateral(a f64, b f64, c f64) bool {
    return is_triangle(a, b, c) && a == b && b == c
}

fn is_isosceles(a f64, b f64, c f64) bool {
    return is_triangle(a, b, c) && (a == b || b == c || c == a)
}

fn is_scalene(a f64, b f64, c f64) bool {
    return is_triangle(a, b, c) &&  a != b && b != c && c != a
}

fn is_triangle(a f64, b f64, c f64) bool {
    return a + b >= c && b + c >= a && a + c >= b
}

Tags:

construct:add
construct:boolean
construct:double
construct:f64
construct:function
construct:invocation
construct:logical-and
construct:logical-or
construct:module
construct:number
construct:parameter
construct:return
construct:string
construct:throw
construct:visibility
paradigm:functional
paradigm:object-oriented
technique:boolean-logic
technique:exceptions

from vlang.

ErikSchierboom avatar ErikSchierboom commented on August 16, 2024

Exercise: prime-factors

Code

module main

fn prime_factors(n i64) []i64 {
	mut prime_list := []i64{}
	mut prime := 2
	mut number := n
	for number != 1 {
		if number % prime == 0 {
			prime_list << prime
			number /= prime
			continue
		}
		prime++
	}
	return prime_list
}

Tags:

construct:assignment
construct:continue
construct:for-loop
construct:if
construct:integer
construct:integral-number
construct:invocation
construct:method
construct:module
construct:number
construct:parameter
construct:return
construct:variable
construct:visibility-modifiers
paradigm:imperative
paradigm:object-oriented
technique:looping

from vlang.

ErikSchierboom avatar ErikSchierboom commented on August 16, 2024

Exercise: accumulate

Code

module main

fn accumulate_ints(values []int, operation fn (int) int) []int {
	mut result := []int{}

	for i in values {
		result << operation(i)
	}

	return result
}

// Because V functions cannot be overloaded[1], make another function
//  called `accumulate_strs` that does the same thing for strings
// instead of ints

fn accumulate_strs(values []string, operation fn (string) string) []string {
	mut result := []string{}
	for i in values {
		result << operation(i)
	}

	return result
}

Tags:

construct:assignment
construct:bitwise-shift
construct:comment
construct:for-loop
construct:function
construct:function-type
construct:implicit-conversion
construct:initializer
construct:int
construct:integral-number
construct:invocation
construct:lambda
construct:left-shift
construct:module
construct:number
construct:parameter
construct:return
construct:string
construct:variable
construct:visibility-modifiers
paradigm:functional
paradigm:imperative
paradigm:object-oriented
technique:bit-manipulation
technique:bit-shifting
technique:higher-order-functions
technique:looping

from vlang.

ErikSchierboom avatar ErikSchierboom commented on August 16, 2024

Exercise: secret-handshake

Code

module main

enum Command as u8 {
	wink						= 0b00001
	double_blink		= 0b00010
	close_your_eyes	= 0b00100
	jump						= 0b01000
	reverse					= 0b10000
}

pub fn commands(encoded_message int) []Command {
	mut ret := []Command{}
	for cmd in [Command.wink, Command.double_blink, Command.close_your_eyes, Command.jump] {
		if encoded_message & int(cmd) != 0 { ret << cmd }
	}
	if encoded_message & int(Command.reverse) != 0 { ret.reverse_in_place() }
	
	return ret
}

Tags:

construct:binary
construct:bitwise-and
construct:enum
construct:for-loop
construct:hexadecimal-number
construct:if-expression
construct:initializer
construct:integral-number
construct:invocation
construct:left-shift
construct:method
construct:module
construct:number
construct:parameter
construct:return
construct:set
construct:visibility-modifiers
paradigm:bitwise
paradigm:imperative
paradigm:object-oriented
technique:bit-manipulation
technique:looping
uses:Command[]
uses:u8

from vlang.

ErikSchierboom avatar ErikSchierboom commented on August 16, 2024

Exercise: gigasecond

Code

// ---------------------------------------------------------------------------
// exercism.org
// V Track Exercise: gigasecond
// Contributed: Anthony J. Borla ([email protected])
// ---------------------------------------------------------------------------

module main

import time

fn add_gigasecond(t time.Time) time.Time {
   return time.Time{ unix : (t.unix + 1000000000) }
}

Tags:

construct:add
construct:big-int
construct:comment
construct:fn
construct:function
construct:import
construct:initializer
construct:int
construct:integral-number
construct:invocation
construct:method
construct:module
construct:number
construct:parameter
construct:return
construct:struct
construct:time.Time
construct:time.Time.constructor
construct:time.Time.unix
construct:underscored-number
construct:variable
construct:visibility-modifiers
paradigm:functional
paradigm:object-oriented

from vlang.

ErikSchierboom avatar ErikSchierboom commented on August 16, 2024

Exercise: all-your-base

Code

module main

import math

fn rebase(input_base int, digits []int, output_base int) ![]int {
	if input_base < 2 {
		return error('input base must be >= 2')
	}
	if output_base < 2 {
		return error('output base must be >= 2')
	}
	if digits.len < 1 {
		return [0]
	}

	mut res := []int{}
	mut deci := int(0)
	for idx, e in digits.reverse() {
		if e < 0 || e >= input_base {
			return error('all digits must satisfy 0 <= d < input base')
		}
		deci += int(math.powi(input_base, idx) * e)
	}
	for deci > 0 {
		res << deci % output_base
		deci /= output_base
	}
	return if res.len == 0 {
		[0]
	} else {
		res.reverse()
	}
}

Tags:

construct:assignment
construct:bitwise-left-shift
construct:boolean
construct:char
construct:error
construct:explicit-conversion
construct:for-loop
construct:function
construct:if-expression
construct:implicit-conversion
construct:indexing
construct:int
construct:integral-number
construct:invocation
construct:lambda
construct:left-shift
construct:logical-or
construct:method
construct:module
construct:multiply
construct:number
construct:parameter
construct:return
construct:short-circuiting
construct:vector
construct:visibility-modifiers
paradigm:functional
paradigm:imperative
paradigm:object-oriented
technique:bit-manipulation
technique:boolean-logic
technique:exceptions
technique:higher-order-functions
technique:looping
technique:type-conversion

from vlang.

ErikSchierboom avatar ErikSchierboom commented on August 16, 2024

Exercise: bob

Code

module main

fn response(hey_bob string) string {
  mut is_silence := true
  mut is_question := false
  mut contains_upper := false
  mut contains_lower := false

  for ch in hey_bob.bytes() {
    if ch.is_space() {
      continue
    }
    is_silence = false

    if ch == u8(`?`) {
      // The last non-whitespace character is a question mark.
      is_question = true
      continue
    }
    is_question = false

    if ch.is_letter() {
      if ch.is_capital() {
        contains_upper = true
      } else {
        contains_lower = true
      }
    }
  }

  if is_silence {
    return 'Fine. Be that way!'
  }

  if contains_upper && !contains_lower {
    if is_question {
      return "Calm down, I know what I'm doing!"
    }
    return 'Whoa, chill out!'
  }

  if is_question {
    return 'Sure.'
  }
  return 'Whatever.'
}

Tags:

construct:assignment
construct:boolean
construct:byte
construct:char
construct:comment
construct:continue
construct:for-loop
construct:function
construct:if
construct:implicit-conversion
construct:invocation
construct:logical-and
construct:method
construct:module
construct:parameter
construct:return
construct:string
construct:variable
construct:visibility-modifiers
paradigm:imperative
paradigm:object-oriented
technique:boolean-logic
technique:looping

from vlang.

ErikSchierboom avatar ErikSchierboom commented on August 16, 2024

Exercise: matching-brackets

Code

module main

import datatypes { Stack }

const (
    opening = ['(', '[', '{']
    closing = [')', ']', '}']
    not_found = -1
)

fn is_paired(input string) bool {
    mut stack := Stack[string]{}

    for bracket in input.split('') {
        if bracket in opening {
            stack.push(bracket)    
        } else if bracket in closing {
            o := stack.pop() or { return false }
            c_i := closing.index(bracket)
            o_i := opening.index(o)
    
            if c_i == not_found || o_i == not_found || c_i != o_i {
                return false
            }
        }
    }
    return stack.is_empty()
}

Tags:

construct:assignment
construct:boolean
construct:char
construct:const
construct:constructor
construct:dictionary
construct:field
construct:for-loop
construct:if
construct:implicit-conversion
construct:indexing
construct:initializer
construct:int
construct:integral-number
construct:invocation
construct:logical-or
construct:method
construct:module
construct:number
construct:object-initializer
construct:parameter
construct:return
construct:set
construct:string
construct:variable
construct:visibility-modifiers
paradigm:imperative
paradigm:object-oriented
technique:boolean-logic
technique:looping
uses:Stack
uses:Stack<T>

from vlang.

ErikSchierboom avatar ErikSchierboom commented on August 16, 2024

Exercise: protein-translation

Code

module main

import arrays { chunk }

fn to_protein(codon string) string {
	return match codon {
		'AUG' { 'Methionine' }
		'UUU', 'UUC' { 'Phenylalanine' }
		'UUA', 'UUG' { 'Leucine' }
		'UCU', 'UCC', 'UCA', 'UCG' { 'Serine' }
		'UAU', 'UAC' { 'Tyrosine' }
		'UGU', 'UGC' { 'Cysteine' }
		'UGG' { 'Tryptophan' }
        'UAA', 'UAG', 'UGA' { 'STOP' }
		else { 'UNKNOWN' }
	}
}

fn codons(rna string) []string {
	return chunk(rna.split(''), 3).map(it.join(''))
}

fn proteins(strand string) ![]string {
    mut result := []string{}
    for protein in codons(strand).map(to_protein(it)) {
        match protein {
            'STOP' { return result }
            'UNKNOWN' { return error('Invalid codon') }
            else { result << protein }
        }
    }
    return result
}

Tags:

construct:assignment
construct:bitwise-left-shift
construct:char
construct:empty-struct-initializer
construct:error
construct:fn
construct:for-loop
construct:import
construct:invocation
construct:lambda
construct:match-expression
construct:module
construct:parameter
construct:return
construct:set
construct:string
construct:throw
construct:tuple
construct:variable
construct:visibility-modifiers
paradigm:functional
paradigm:imperative
paradigm:object-oriented
technique:bit-manipulation
technique:bit-shifting
technique:exceptions
technique:higher-order-functions
technique:looping

from vlang.

ErikSchierboom avatar ErikSchierboom commented on August 16, 2024

Exercise: connect

Code

module main

const side_none = 0

// Bitwise XOR with a side can be used to find a player's other side.
const side_opposite = 1

const side_top = 2

const side_bottom = 3

const side_left = 4

const side_right = 5

struct Cell {
	row    int
	column int
	side   int = side_none
}

// Each cell has 6 adjacent cells.
const deltas = [
	Cell{
		row: 0
		column: -1
	},
	Cell{
		row: 0
		column: 1
	},
	Cell{
		row: -1
		column: 0
	},
	Cell{
		row: 1
		column: 0
	},
	Cell{
		row: -1
		column: 1
	},
	Cell{
		row: 1
		column: -1
	},
]

fn winner(board []string) ?rune {
	row_count := board.len
	column_count := (board[0].len + 1) >> 1

	mut pending := []Cell{cap: (row_count + 2) * (column_count + 2)}
	for column in 0 .. column_count {
		pending << Cell{
			row: -1
			column: column
			side: side_top
		}
		pending << Cell{
			row: row_count
			column: column
			side: side_bottom
		}
	}
	for row in 0 .. row_count {
		pending << Cell{
			row: row
			column: -1
			side: side_left
		}
		pending << Cell{
			row: row
			column: column_count
			side: side_right
		}
	}

	mut reached := [][]int{len: row_count, init: []int{len: column_count, init: side_none}}

	for pending.len > 0 {
		current := pending.pop()

		// "Player `O`" plays from top to bottom,
		// "Player `X`" plays from left to right.
		player := if current.side <= side_bottom { `O` } else { `X` }

		// We consider the 6 cells adjacent to current, excluding those we don't occupy.
		// If any have not previously been reached, we queue them.
		// If any have been reached from the opposite side, we have won.
		for delta in deltas {
			row := current.row + delta.row
			column := current.column + delta.column
			if row < 0 || row >= row_count || column < 0 || column >= column_count {
				continue
			}
			occupant := board[row][row + 2 * column]
			if occupant != player {
				continue
			}
			if reached[row][column] == current.side {
				continue
			}
			if reached[row][column] == side_none {
				reached[row][column] = current.side
				pending << Cell{
					row: row
					column: column
					side: current.side
				}
				continue
			}
			assert reached[row][column] == current.side ^ side_opposite
			return player
		}
	}

	// No player has won.
	return none
}

Tags:

construct:add
construct:assignment
construct:assert
construct:bitwise-xor
construct:boolean
construct:comment
construct:const
construct:continue
construct:field-initializer
construct:for-loop
construct:function
construct:if
construct:initializer
construct:indexing
construct:int
construct:integral-number
construct:invocation
construct:lambda
construct:left-shift
construct:logical-or
construct:method
construct:module
construct:multiply
construct:named-argument
construct:number
construct:optional
construct:parameter
construct:return
construct:right-shift
construct:struct
construct:subtract
construct:variable
construct:visibility-modifiers
paradigm:functional
paradigm:imperative
paradigm:object-oriented
technique:bit-manipulation
technique:bit-shifting
technique:boolean-logic
technique:higher-order-functions
technique:looping

from vlang.

ErikSchierboom avatar ErikSchierboom commented on August 16, 2024

Exercise: diamond

Code

module main

import strings

fn generate_row(index int, n int) string {
        if index > n {
                return generate_row(2 * n - index, n)
        }
        len := 2 * n + 1
        mut builder := strings.new_builder(len)
        builder.write_string(strings.repeat(u8(` `), n - index))
        builder.write_rune(`A` + index)
        if index > 0 {
                builder.write_string(strings.repeat(u8(` `), 2 * index - 1))
                builder.write_rune(`A` + index)
        }
        builder.write_string(strings.repeat(u8(` `), n - index))
        assert builder.len == len
        return builder.str()
}

fn rows(letter rune) []string {
        assert `A` <= letter && letter <= `Z`
        n := int(letter - `A`)
        len := 2 * n + 1
        mut result := []string{cap: len}
        for i in 0 .. len {
                result << generate_row(i, n)
        }
        return result
}

Tags:

construct:add
construct:assert
construct:assignment
construct:boolean
construct:for-loop
construct:function
construct:if
construct:implicit-conversion
construct:indexing
construct:int
construct:integral-number
construct:invocation
construct:lambda
construct:left-shift
construct:method
construct:multiply
construct:named-argument
construct:number
construct:object
construct:parameter
construct:return
construct:right-shift
construct:string
construct:subtract
construct:throw
construct:tuple
construct:u8
construct:variable
paradigm:functional
paradigm:imperative
paradigm:object-oriented
technique:bit-manipulation
technique:bit-shifting
technique:exceptions
technique:higher-order-functions
technique:looping

from vlang.

ErikSchierboom avatar ErikSchierboom commented on August 16, 2024

Exercise: acronym

Code

module main

fn abbreviate(phrase string) string {
    return phrase.replace_each(['-', ' ', '_', '']) // Replace hyphens with spaces and remove other undesired characters
        .split(' ')                                // Split into words
        .filter(it.len > 0)                        // Filter out empty words
        .map(it[0].ascii_str().to_upper())         // Get the first letter of each word and convert to uppercase
        .join('')                                  // Join the results to form the acronym
}

Tags:

construct:char
construct:indexing
construct:invocation
construct:lambda
construct:method
construct:module
construct:number
construct:parameter
construct:return
construct:string
construct:comment
construct:method-overloading
construct:tuple
construct:variable
construct:visibility-modifiers
paradigm:functional
paradigm:object-oriented
technique:higher-order-functions

from vlang.

ErikSchierboom avatar ErikSchierboom commented on August 16, 2024

Exercise: word-search

Code

module main

const directions = [-1, 0, 1]

struct Pair {
	column int
	row    int
}

struct WordLocation {
	start Pair
	end   Pair
}

// Checks if the given position is within the grid boundaries
fn is_valid_position(row int, column int, rows int, columns int) bool {
	return row >= 0 && row < rows && column >= 0 && column < columns
}

// Moves from a starting position in the specified direction for a given distance
fn move_in_direction(row int, column int, delta_row int, delta_column int, distance int) Pair {
	return Pair{
		column: column + delta_column * distance,
		row: row + delta_row * distance,
	}
}

// Searches for a word in the grid starting from a specific position and following a given direction
fn search_word_in_direction(grid []string, word string, start_row int, start_column int, delta_row int, delta_column int) ?WordLocation {
    mut position := Pair{column: 0, row: 0}
	for i in 0..word.len {
		position = move_in_direction(start_row, start_column, delta_row, delta_column, i)
		if !is_valid_position(position.row, position.column, grid.len, grid[0].len) || grid[position.row][position.column] != word[i] {
			return none
		}
	}
	return ?WordLocation{
        start: Pair{column: start_column + 1, row: start_row + 1},
        end: Pair{column: position.column + 1, row: position.row + 1}
    }
}

// Searches for a word in the grid starting from a specific position
fn find_word_starting_at(grid []string, word string, start_row int, start_column int) ?WordLocation {
	for delta_row in directions {
		for delta_column in directions {
			if delta_row == 0 && delta_column == 0 {
				continue
			}
			if location := search_word_in_direction(grid, word, start_row, start_column, delta_row, delta_column) {
				return location
			}
		}
	}
	return none
}

// Searches for multiple words in the grid and returns their positions
fn search(grid []string, words_to_search_for []string) map[string]?WordLocation {
	mut result := map[string]?WordLocation{}
	for word in words_to_search_for {
		mut found_location := ?WordLocation(none)
		for row in 0..grid.len {
			for column in 0..grid[0].len {
				if location := find_word_starting_at(grid, word, row, column) {
					found_location = location
					break
				}
			}
			if found_location != none {
				break
			}
		}
		result[word] = found_location
	}
	return result
}

Tags:

construct:add
construct:assignment
construct:boolean
construct:break
construct:comment
construct:const
construct:constructor
construct:continue
construct:field
construct:for-loop
construct:if
construct:index-assignment
construct:index-expression
construct:initializer
construct:int
construct:integral-number
construct:invocation
construct:lambda
construct:logical-and
construct:logical-or
construct:map
construct:method
construct:module
construct:multiply
construct:named-argument
construct:number
construct:parameter
construct:return
construct:string
construct:struct
construct:subtract
construct:variable
construct:visibility-modifiers
paradigm:functional
paradigm:imperative
paradigm:object-oriented
technique:boolean-logic
technique:higher-order-functions
technique:looping
uses:map

from vlang.

ErikSchierboom avatar ErikSchierboom commented on August 16, 2024

Exercise: affine-cipher

Code

module main

import math

struct Key {
	a int
	b int
}

// Returns a non-negative value, even if a is negative.
fn mod(a int, b int) int {
	assert 0 < b
	r := a % b
	return if 0 <= r { r } else { b + r }
}

// modular multiplicative inverse
fn mmi(a int, m int) int {
	_, _, y := math.egcd(m, a)
	return int(y)
}

fn encode(phrase string, key Key) !string {
	if key.a == 0 || math.gcd(26, key.a) != 1 {
		return error('a and m must be coprime.')
	}
	mut buffer := []u8{cap: phrase.len * 6 / 5}
	for ch in phrase {
		if !ch.is_alnum() {
			continue
		}
		if buffer.len % 6 == 5 {
			buffer << u8(` `)
		}
		if ch.is_digit() {
			buffer << ch
			continue
		}
		i := if ch >= `a` { int(ch - `a`) } else { int(ch - `A`) }
		assert 0 <= i && i < 26
		j := mod(key.a * i + key.b, 26)
		buffer << u8(`a` + j)
	}
	return buffer.bytestr()
}

fn decode(phrase string, key Key) !string {
	if key.a == 0 || math.gcd(26, key.a) != 1 {
		return error('a and m must be coprime.')
	}
	a_inverse := mmi(key.a, 26)
	assert mod(a_inverse * key.a, 26) == 1
	mut buffer := []u8{cap: phrase.len}
	for ch in phrase {
		if !ch.is_alnum() {
			continue
		}
		if ch.is_digit() {
			buffer << ch
			continue
		}
		j := int(ch - `a`)
		assert 0 <= j && j < 26
		i := mod(a_inverse * (j - key.b), 26)
		buffer << u8(`a` + i)
	}
	return buffer.bytestr()
}

Tags:

construct:add
construct:assignment
construct:assert
construct:bitwise-left-shift
construct:boolean
construct:char
construct:comment
construct:constructor
construct:continue
construct:divide
construct:else
construct:enum
construct:error
construct:fn
construct:for-loop
construct:if
construct:implicit-conversion
construct:import
construct:int
construct:integral-number
construct:invocation
construct:logical-and
construct:logical-or
construct:method
construct:module
construct:multiply
construct:named-argument
construct:number
construct:parameter
construct:return
construct:short
construct:string
construct:struct
construct:subtract
construct:ternary
construct:tuple
construct:u8
construct:variable
construct:visibility-modifiers
paradigm:imperative
paradigm:object-oriented
technique:bit-manipulation
technique:bit-shifting
technique:boolean-logic
technique:looping

from vlang.

ErikSchierboom avatar ErikSchierboom commented on August 16, 2024

Exercise: armstrong-numbers

Code

module main

import math

pub fn is_armstrong_number(number u32) bool {
    mut digits := []u32{}
    mut n := number
    for n != 0 {
        digits << n % 10
        n = n / 10
    }
    mut sum := i64(0)
    for digit in digits {
        sum += math.powi(digit, digits.len)
    }
    return sum == number
}

Tags:

construct:assignment
construct:boolean
construct:divide
construct:double
construct:explicit-conversion
construct:fn
construct:floating-point-number
construct:for-loop
construct:if-expression
construct:implicit-conversion
construct:invocation
construct:loop
construct:number
construct:parameter
construct:return
construct:set
construct:tuple
construct:u32
construct:u64
construct:variable
construct:visibility-modifiers
paradigm:imperative
paradigm:functional
paradigm:object-oriented
technique:looping
technique:type-conversion
uses:math.set
uses:tuple

from vlang.

ErikSchierboom avatar ErikSchierboom commented on August 16, 2024

Exercise: difference-of-squares

Code

module main

import math

pub fn square_of_sum(n u32) u32 {
	mut res := u32(0)
	for e in 1 .. n + 1 {
		res += e
	}
	return u32(math.powi(res, 2))
}

pub fn sum_of_squares(n u32) u32 {
	mut res := u32(0)
	for e in 1 .. n + 1 {
		res += u32(math.powi(e, 2))
	}
	return res
}

pub fn difference(n u32) u32 {
	return square_of_sum(n) - sum_of_squares(n)
}

Tags:

construct:add
construct:assignment
construct:double
construct:fn
construct:floating-point-number
construct:for-loop
construct:import
construct:invocation
construct:loop
construct:method
construct:module
construct:number
construct:parameter
construct:return
construct:subtract
construct:u32
construct:variable
construct:visibility
paradigm:imperative
paradigm:functional
paradigm:object-oriented
technique:looping

from vlang.

ErikSchierboom avatar ErikSchierboom commented on August 16, 2024

Exercise: complex-numbers

Code

module main

import math

struct Complex {
  re f64
  im f64
}

// build a Complex number
pub fn Complex.new(real f64, imaginary f64) Complex {
    return Complex {
        re: real,
        im: imaginary
    }
}

pub fn (c Complex) real() f64 {
    return c.re
}

pub fn (c Complex) imaginary() f64 {
    return c.im
}

pub fn (c Complex) conjugate() Complex {
    return Complex {
        re: c.re,
        im: -c.im
    }
}

pub fn (c Complex) absolute_square() f64 {
    return c.re * c.re + c.im * c.im
}

pub fn (c Complex) abs() f64 {
    return math.sqrt(c.absolute_square())
}

pub fn (c Complex) add(other Complex) Complex {
    return Complex {
        re: c.re + other.re,
        im: c.im + other.im
    }
}

pub fn (c Complex) sub(other Complex) Complex {
    return Complex {
        re: c.re - other.re,
        im: c.im - other.im
    }
}

pub fn (c Complex) exp() Complex {
    return Complex {
        re: math.cos(c.im),
        im: math.sin(c.im)
    }.mul_by_real(math.exp(c.re))
}

pub fn (c Complex) mul(other Complex) Complex {
    return Complex {
        re: c.re * other.re - c.im * other.im,
        im: c.im * other.re + c.re * other.im
    }
}

pub fn (c Complex) div(other Complex) Complex {
    return c.mul(other.conjugate()).div_by_real(other.absolute_square())
}

// add a real number 'r' to complex number 'c'
//  c + r
pub fn (c Complex) add_real(r f64) Complex {
    return Complex {
        re: c.re + r,
        im: c.im
    }
}

// add a complex number 'c' to a real number 'r':
//  r + c
pub fn (c Complex) real_add(r f64) Complex {
    return c.add_real(r)
}

// subtract a real number 'r' from a complex number 'c':
//  c - r
pub fn (c Complex) sub_real(r f64) Complex {
    return Complex {
        re: c.re - r,
        im: c.im
    }
}

// subtract a complex number 'c' from 'r':
//  r - c
pub fn (c Complex) real_sub(r f64) Complex {
    return Complex {
        re: r - c.re,
        im: -c.im
    }
}

// multiply a complex number 'c' by real number 'r'
//  c * r
pub fn (c Complex) mul_by_real(r f64) Complex {
    return Complex {
        re: c.re * r,
        im: c.im * r
    }
}

// multiply a real number 'r' by a complex number 'c':
//  r * c
pub fn (c Complex) real_mul(r f64) Complex {
    return c.mul_by_real(r)
}

// divide complex number 'c' by real number 'r'
//  c / r
pub fn (c Complex) div_by_real(r f64) Complex {
    return Complex {
        re: c.re / r,
        im: c.im / r
    }
}

// divide a real number 'r' by a complex number 'c'
//  r / c
pub fn (c Complex) real_div(r f64) Complex {
    return c.conjugate().mul_by_real(r).div_by_real(c.absolute_square())
}

Tags:

construct:add
construct:comment
construct:divide
construct:double
construct:field
construct:floating-point-number
construct:fn
construct:import
construct:invocation
construct:method
construct:multiply
construct:named-argument
construct:number
construct:parameter
construct:return
construct:struct
construct:subtract
construct:variable
construct:visibility-modifiers
paradigm:functional
paradigm:object-oriented

from vlang.

ErikSchierboom avatar ErikSchierboom commented on August 16, 2024

Exercise: perfect-numbers

Code

module main

pub enum Number {
	perfect
	abundant
	deficient
}

// Returns a `Result` type, now using `!` instead of `?`
pub fn classify(candidate int) !Number {
	if candidate <= 0 {
		// returning an error with the exact message expected by the tests
		return error('Classification is only possible for positive integers.')
	}

	mut aliquot_sum := 0 // making `aliquot_sum` mutable
	for i in 1 .. candidate {
		if candidate % i == 0 {
			aliquot_sum += i
		}
	}

	// The rest of your function remains unchanged
	if aliquot_sum == candidate {
		return Number.perfect
	} else if aliquot_sum > candidate {
		return Number.abundant
	} else {
		return Number.deficient
	}
}

fn main() {
	// handling potential errors with `or` block
	result := classify(28) or {
		println(err) // directly use `err` without redefinition
		return
	}
	println(result)
}

Tags:

construct:assignment
construct:char
construct:comment
construct:enum
construct:error
construct:for-loop
construct:function
construct:if
construct:implicit-conversion
construct:int
construct:integral-number
construct:invocation
construct:loop
construct:number
construct:parameter
construct:return
construct:using-directive
construct:variable
construct:visibility-modifiers
paradigm:imperative
paradigm:object-oriented
technique:looping

from vlang.

ErikSchierboom avatar ErikSchierboom commented on August 16, 2024

This is an automated comment

Hello 👋 Next week we're going to start using the tagging work people are doing on these. If you've already completed the work, thank you! If you've not, but intend to this week, that's great! If you're not going to get round to doing it, and you've not yet posted a comment letting us know, could you please do so, so that we can find other people to do it. Thanks!

from vlang.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.