Notes, summaries, assignments, exams, and exercises for Computer science for Primary education

Java Data Structures: Sorted Lists and Hash Tables

Computer science3.32 KB

Sorted Linked List Insertion

The following method, insertAtSorted(T x), demonstrates how to insert an element into a sorted linked list while maintaining the correct order.

public void insertAtSorted(T x) {
    if (this.length == 0) {
        this.firstNode = nn;
        this.lastNode = nn;
    } else if (((Comparable)x).compareTo(this.firstNode.data) < 0) {
        nn.next = this.firstNode;
        this.firstNode = nn;
    } else {
        SNode<T> curr = this.firstNode;
        while (((Comparable)x).compareTo(curr.next.data) >= 0) {
            curr = curr.next;
        }
        nn.next = curr.next;
        curr.next = nn;
    }
    this.length++;
}

Priority Queue Enqueue Implementation

The enqueuer method handles inserting items...

Continue reading "Java Data Structures: Sorted Lists and Hash Tables" »

Java Linked List Implementation: Insert, Search and Delete Operations

Computer science4.32 KB

Implementación de una Lista Enlazada en Java

A continuación se presenta la clase Lista, que implementa una lista enlazada simple con operaciones de inserción, búsqueda, recorrido y eliminación.

public class Lista {

private Nodo com;

public Lista() {
this.com = null;
}

public Nodo getCom() {
return this.com;
}

public void setCom(Nodo com) {
this.com = com;
}

public void recorrer() {
Nodo p;
p = this.com;
while(p != null) {
System.out.println(p);
p = p.getSig();
}
}

public void addBegin(int dato) {
Nodo nodo = new Nodo();
nodo.setInfo(dato);
nodo.setSig(this.com);
this.com = nodo;
}
...
Continue reading "Java Linked List Implementation: Insert, Search and Delete Operations" »

Creating and Managing Coach and Activity Tables in SQL

Computer science4.29 KB

1. Create Table Coach

CoachID INT PRIMARY KEY,

CoachName VARCHAR(20) NOT NULL,

Sports VARCHAR(15) NOT NULL,

DOJ DATE NOT NULL,

Gender CHAR(1) NOT NULL,

Salary INT NOT NULL


INSERT INTO Coach (CoachID, CoachName, Sports, DOJ, Gender, Salary)

VALUES

(1001, 'Mulund Gogoi', 'Boxing', '2004-09-01', 'M', 40000),

(1002, 'Arnab Duwara', 'Karate', '1999-10-01', 'M', 60000),

(1003, 'Nayan Bora', 'Arm Wrestling', '2005-02-28', 'M', 50000),

(1004, 'Devesh Hazarika', 'Basketball', '2010-05-05', 'M', 25000),

(1005, 'Chetan Sharma', 'Swimming', '2010-03-31', 'M', 25000),

(1006, 'Lakshmi Devi', 'Boxing', '2012-01-01', 'F', 22000);


3. Queries for Questions:

a) Display the Maximum and Minimum Salary of the Coaches

SELECT MAX(Salary) AS Max_Salary, MIN(Salary) AS Min_Salary

...
Continue reading "Creating and Managing Coach and Activity Tables in SQL" »

4rpl Scripting Reference: Variables, Math, Loops, Functions and Units

Computer science6.25 KB

https://knucklecracker.com/wiki/doku.php?id=4rpl:start#stack

Core Concepts

  • Variables: ->IntoVar, <-FromVar, "Var" NotPersist (won't persist across saves), GetType results "STRING INT FLOAT LIST TABLE NULL", IsNull
  • a(b) warps to b a, e.g. add(1 2) becomes 1 2 add

Math

  • Basic math: add, sub, mul, div, mod, mod2 (different negative results). 1 2 add ->Three / add(1 2) ->Three
  • More math: RandInt, RandFloat, asint/asfloat, approximately (float compare), BallisticArcLateral, BallisticArcPos, SignalGenerator (square/saw/etc. waveforms), standard abs/ceil/floor etc.
  • Vectors and angles: Vec1, Vec2, Distance, DistanceCell (2D), ShortestAngle, VectorAngleCell, VectorAngle, RotateTowards, RotateTowardsCell, DistancePointLine(point lineStart lineEnd)
...
Continue reading "4rpl Scripting Reference: Variables, Math, Loops, Functions and Units" »

Understanding ALU Architecture and Processor Pipeline Efficiency

Computer science2.51 KB

ALU Architecture and Components

The ALU (Arithmetic Logic Unit) is formed by the following components:

  • Operational Circuit: Contains the circuitry necessary to perform operations with data from the input records (REN). This circuit has a command input to select the type of operation to be performed (e.g., addition, subtraction).
  • Input Records (REN): These store the data or operands involved in a statement before the transaction is completed by the operational circuit. They are also used to store intermediate or final results.
  • Accumulator Register: Saves results of operations carried out by the operational circuit. It is connected to the input records for feedback regarding chained transactions and has a direct connection to the data bus to send
...
Continue reading "Understanding ALU Architecture and Processor Pipeline Efficiency" »

C# Console Programs: Digit Sum, Dice Rolls, Averages and Matrix Sums

Computer science5.79 KB

The following collection of C# console methods demonstrates digit sums, dice rolls, coin tosses, averages, array squares and matrix calculations. Each method is written in a simple, readable style suitable for beginners.

1. Digit Sum of a Number

public static void vsotastevk()
{
    int n, vsota = 0, r;
    Console.WriteLine("Vnesi stevilo: ");
    n = int.Parse(Console.ReadLine());
    while (n != 0)
    {
        r = n % 10;
        n = n / 10;
        vsota = vsota + r;
    }
    Console.WriteLine("Vsota stevk stevila je: " + vsota);
    Console.ReadLine();
}

2. Dice Throw Simulation

public static void metanjekock()
{
    Random randNum = new Random();
    int Stevilometa = 1;
    int kocka1;
    int kocka2;
    int stetje1 = 0;
    int stetje2
...
Continue reading "C# Console Programs: Digit Sum, Dice Rolls, Averages and Matrix Sums" »

Mastering Java Core Concepts: Generics, Collections, Events, and Swing

Computer science6.82 KB

Java Generics: Methods and Classes

Java Generics enable programmers to specify, with a single method declaration, a set of related methods, or with a single class declaration, a set of related types, respectively. Generics also provide compile-time type safety, which allows programmers to catch invalid types at compile time, preventing runtime errors.

Generics Example: ArrayList

Consider the following example demonstrating generics with an ArrayList:

1. import java.util.*;
2. class TestGenerics1 {
3.   public static void main(String args[]) {
4.     ArrayList<String> list = new ArrayList<String>();
5.     list.add("rahul");
6.     list.add("jai");
7.     // list.add(32); // compile-time error if uncommented
8.     String s = list.get(
...
Continue reading "Mastering Java Core Concepts: Generics, Collections, Events, and Swing" »

Fruteria: Añadir, Comprar y Pagar Frutas

Computer science3.49 KB

int opcion=0;

double cantidad, vuelto;

double pago, total = 0;

string[,] fruta = { { 'Manzana', '4.9' }, { 'Pera', '5.5' }, { 'Naranja', '8.6' }, { 'Platano', '2.7' } ,{ 'Fresa', '1.9' } ,{ 'Piña', '2.4' }, { 'Papaya', '4.2' }, { 'Sandia', '3.4' } ,{ 'Durazno', '3.5' } };

String[,] añaFruta = newString[50, 5];

int i=0, j=0;

int añadir = 0,tFruta=0;

do{

do{

i = 0;

Console.Write('_________________________ ' +

'FRUTERIA .... '+

'1) AÑADIR FRUTA. ');

while (i < 9)

{ Console.Write(i+2+') '+fruta[i,0]+' ');

i++;

}

if(añadir>0)

{j = 11;

i = 0;

tFruta = añadir+9;

while (i < añadir)

{Console.Write(j + ') ' + añaFruta[i, 0] + ' ');

j++;i++;

}

}

else { tFruta = 9; }

Console.Write(tFruta + 2+') Pagar. ');

opcion = int.Parse(Console.ReadLine(

...
Continue reading "Fruteria: Añadir, Comprar y Pagar Frutas" »

Java Implementation of AVL Tree Data Structure

Computer science5.65 KB

AVL Tree Class Implementation in Java

The following source code implements a generic self-balancing AVL Tree (AVLTree<T extends Comparable<T>>) in Java, supporting insertion, deletion, rotation balancing, search, and edge counting.

Class Definition and Constructors

public class AVLTree<T extends Comparable<T>> {
    private AVLNode<T> raiz;
    String cadena = "";

    public AVLTree() {
        raiz = null;
    }

    public AVLNode<T> getRaiz() {
        return raiz;
    }

    public T getInfoRaiz() {
        return raiz.getInfo();
    }

Search Operations

    public AVLNode<T> find(T info) {
        if (raiz == null) {
            return null;
        }
        return findR(raiz, info);
    }

    private
...
Continue reading "Java Implementation of AVL Tree Data Structure" »

Implementação de Listas Ligadas em C++ (CRUD)

Computer science3.44 KB

Listas Ligadas em C++: Adicionar, Excluir, Buscar e Imprimir

Implementação básica de uma lista simplesmente ligada em C++, cobrindo as operações essenciais de manipulação de dados.

Configuração Inicial em C++

#include <iostream>
using namespace std;

Classe Node (Nó)

Define a estrutura fundamental de cada elemento da lista.

class Node {
    public:
        int value; // Pode ser implementado qualquer tipo de dados aqui.
        Node *next;
        
        Node () {
            next = NULL; // Construtor Padrão
        }
        
        Node (int _value) { // Construtor com Atribuição de Valor
            value = _value;
            next = NULL;
        }
};

Classe List (Lista Ligada)

Gerencia a coleção de nós e as operações...

Continue reading "Implementação de Listas Ligadas em C++ (CRUD)" »