programming – How do I write a Prolog program that implements the following predicates for an AVL tree

An AVL tree is a binary tree for which a special condition holds throughout the tree, namely, that at every node the height of the left and right subtrees differ by at most 1. A binary tree can be defined in terms of 2 predicates:

empty, the empty binary tree
bt(N,T1,T2) that is true if N is the root of a binary tree with left subtree T1 and right subtree T2, where all the items in T1 are less than or equal to N and all the items in T2 are greater than N.

How do I write a Prolog program that implements the following predicates for an AVL tree:

insert(I,T1,T2) is true if T2 is the AVL tree resulting from I being inserted into an AVL tree T1.
display(T) is always true prints the AVL tree to the display.

user interface – Java Programming II Course GUI doesn’t work

I’m doing the Java Programming II MOOC course, and I’m having some problems with the section on GUIs. Whenever I copy and paste the code for the GUI into netbeans, it just results in a bunch of errors, and I have no idea how to fix them. The errors are like “package javafx.application does not exist,” and I don’t know how to make it exist. Do I need to install or import something to make it work?

Here’s a screenshot of what my code looks like right now. It’s just copy and pasted from the website, but you can see where the errors are:
GUI code in Netbeans

reinforcement learning – Resources on Dynamic Programming with Indefinite Recursion

I am trying to explain the value iteration method that is used in reinforcement learning. The method is used to estimate a solution to a recursive equation like:

$ Return(state_t,action_t) = Reward(state_t,state_{t+1}) + gamma * max begin{bmatrix} Return(state_{t+1}, action_{t+1}==’n’)\ Return(state_{t+1}, action_{t+1}==’e’)\ Return(state_{t+1}, action_{t+1}==’w’)\ Return(state_{t+1}, action_{t+1}==’s’) end{bmatrix}$

Normally, if the sub-problems(RHS) are overlapping, a problem like this can be solved using recursive or iterative dynamic programming. However, in the case of reinforcement learning the recursion is often mutual, and thus the dynamic programming solution has no natural point of termination.

The value iteration method works by filling up the memorization table with arbitrary values and then repeatedly applying the recursive equation to every cell in the table until the values in the cell converge.

A similar approach is used in the HITS algorithm where the hub and authority values have mutual recursion.

Are there any good resources, preferably online, that deal with the application of dynamic programming to problems with mutual, indefinite recursion?

dynamic programming: longest palindromic subsequence, recurrence relation question

excel table
Moving from top left down the column then over to the right column, taking ideas from here: https://www.geeksforgeeks.org/longest-palindromic-subsequence-dp-12/
I want to restate the question at the top of the Excel table.
Why do I need to max from T(i,j-1) and T(i+1,j)? Can’t you just take what’s in T(i,j-1)?
I changed the input slightly and I still get the right answer just taking T(i,j-1) when T(i,0) != T(0,j)
excel2

A counterexample would be nice to see.

functional programming – Dominos [Python] CLI Game

from itertools import combinations_with_replacement
from random import sample, choice


def get_starting_board():
    domino = list(map(lambda x: list(x), combinations_with_replacement(range(7), 2)))
    while True:
        player_pieces = sample(domino, 7)
        computer_pieces = sample(list(filter(lambda x: x not in player_pieces, domino)), 7)
        stock_pieces = list(filter(lambda x: x not in (player_pieces + computer_pieces), domino))
        player_doubles = (piece for piece in player_pieces if len(set(piece)) == 1)
        computer_doubles = (piece for piece in computer_pieces if len(set(piece)) == 1)
        doubles = player_doubles + computer_doubles
        if doubles:
            highest_double = max(doubles)
            if highest_double in player_doubles:
                player_pieces.remove(highest_double)
                first_player = 'computer'
            else:
                computer_pieces.remove(highest_double)
                first_player = 'player'
            return {'player': player_pieces, 'computer': computer_pieces,
                    'stock': stock_pieces, 'snake': (highest_double),
                    'turn': first_player}


def get_board_status():
    if len(board('player')) == 0:
        return 'The game is over. You won!'
    elif len(board('computer')) == 0:
        return 'The game is over. The computer won!'
    flat_snake = (num for piece in board('snake') for num in piece)  # Flatten the 2-dimensional list into one list
    for i in range(7):
        if i in board('snake')(0) and i in board('snake')(-1) and flat_snake.count(i) == 8:
            return "The game is over. It's a draw!"
    return 'game_not_done'


def display_board():
    print('=' * 70)
    print('Stock size:', len(board('stock')))
    print('Computer pieces:', len(board('computer')))
    print()
    snake = board('snake')
    if len(snake) > 6:
        for i in range(3):
            print(snake(i), end='')
        print('...', end='')
        for i in range(-3, 0):
            print(snake(i), end='')
    else:
        for p in snake:
            print(p, end='')
    print()
    print('nYour pieces:')
    for i, piece in enumerate(board('player')):
        print(f'{i+1}:{piece}')
    print()


def is_valid_move(move):
    try:
        move = int(move)
    except ValueError:
        return False

    return len(board('player')) >= abs(move)


def make_move(move, player):
    """
    player: can either be "player" or "computer"
    """
    if move == 0:
        stock_piece = choice(board('stock'))
        board('stock').remove(stock_piece)
        board(player).append(stock_piece)
        return
    index = abs(move) - 1
    piece = board(player)(index)
    board(player).remove(piece)
    if move > 0:
        board('snake').append(piece)
    else:
        board('snake').insert(0, piece)


board = get_starting_board()
while True:
    display_board()
    game_state = get_board_status()

    if game_state != 'game_not_done':
        print('Status:', game_state)
        break

    turn = board('turn')
    if turn == 'player':
        print("Status: It's your turn to make a move. Enter your command.")
        while True:
            move = input()
            if is_valid_move(move):
                break
            print('Invalid input. Please try again.')
        move = int(move)
        board('turn') = 'computer'
    else:
        input('Status: Computer is about to make a move. Press Enter to continue...n')
        move = choice(range(-len(board('computer')), len(board('computer'))))
        board('turn') = 'player'

    make_move(move, turn)

functional programming – A beginner’s brainfuck interpreter in Haskell

I am rather new to haskell, and could use some feedback on my code and the decisions I had to make. In my previous project, I made a JSON parser, but relied heavily on guidance from a university course.

This project is a brainfuck interpreter, for which I used nothing but the wiki article on brainfuck (i.e., no foreign design or code, apart from whileM). It was eye-opening in some regards, because I finally used and designed monadic operations by myself. But I am sure there are many more eyes on which I am blind, so please point out where I go wrong or miss more elegant solutions.

This implementation is lacking any IO, because I wanted to create a simple, baseline implementation of stateful computation. The goal is to afterwards use StateT instead of State and combine that with IO, so that I properly learn to use monad transformers.

In particular, I am unsure about the following points:

  1. Data Model

I made a type Tape with a pointer which can be shifted and read from / written to. I use this type for both the data tape and the brainfuck program itself, the instruction tape. The functionality of the two tapes overlap, but not completely. For example, the operation “increment byte at pointer” is only needed for the data tape, while “seek next matching bracket” is only needed for the instruction tape (Lines 1-100).

The question is: Is it okay to make one type for which I implement ALL the functionality, or am I better off splitting it into two types and duplicating the code for the shared instructions (most are shared)? Is there a idiomatic way to have types “inherit” from other types?

  1. Turning it into a State Monad

In lines 149-188, I implement the eight brainfuck operations as state-transforming operations. Even though they do quite different things, I think I need them to have the same type because of the chooseAction function (Line 232): Between different steps of the brainfuck program, the next instruction has to be read from the instruction tape and turned into an actual executable statetransformer. Because this chooseAction function needs to return values of one and the same type, all my monadic operations must have the same type… Right? How is that best achieved?

In my case, I decided to create a type Effect, which currently has two constructors, but which I can easily extend if I create statetransformers with novel effects. Most statetransformers (>, <, +, – etc) have no return value to speak of, so they return None :: Effect. But the sOutp statetransformer, which corresponds to brainfuck’s ‘.’, outputs a byte. This is where IO is going to come in eventually, but for the moment, I just want this byte to be captured by the Effect type and return it to an effect-collecting monadic function whileM :: Monad => m Bool -> m a -> m (a).

Apart from using the IO monad here and turning State into StateT, is there a better way to do what I want here? And do all my 8 monadic brainfuck operations therefore need to have the same type, even though they do such different things?

3)

Lines 150-188 seem a bit verbose, because I seem to be doing the same thing over and over. Am I missing some elegant way here or is this simply the tedious part of the implementation?

Thanks for any inputs!

For line numbers, see this file: https://github.com/el-micha/bf/blob/master/bf.hs

The same code is reproduced below. To run, try:

runTM testtm and runTM testtm2

import Control.Monad
import Data.Char (ord, chr)
import Data.Word (Word8)

-- Implementation without IO. Basecase for future IO extension with MonadTransformers. 

-- ============================================================================
-- Data types for data and instruction tapes and their operations
-- ============================================================================

-- keep track of tape length with tuple (pointer position, tape length so far)
type Bound = (Int, Int)
leftB :: Bound -> Bound
leftB (x, y) = (x-1, y)
rightB :: Bound -> Bound
rightB (x, y) = (x+1, max y (x+1))

-- a type for both the data tape and the instruction tape. 
-- pointer is head of first list. left of pointer is field1(1), right of pointer is field2(0)
-- (1 2 3 4 5 6)
--      ^
-- corresponds to Tape (3, 2, 1) (4, 5, 6) (2, 5)
type Byte = Word8
data Tape = Tape (Byte) (Byte) Bound

zeroes = (0 | _ <- (1..))

emptyTape :: Tape
emptyTape = Tape (0) zeroes ((0, 0) :: Bound)

initTape :: (Byte) -> Tape
initTape (x:xs) = Tape (x) (xs++zeroes) ((0, length xs) :: Bound)

-- shift pointer by one
left :: Tape -> Tape
left (Tape () _ _) = error "Cannot shift tape to left: Is at origin. Bad initialization."
left (Tape (x) _ _) = error "Cannot shift tape to left: Is at leftmost cell."
left (Tape (x:xs) ys b) = Tape xs (x:ys) (leftB b)

right :: Tape -> Tape
right (Tape xs (y:ys) b) = Tape (y:xs) ys (rightB b)

ptrPos (Tape xs ys b) = fst b
tapeLength (Tape xs ys b) = snd b

-- read from pointer position
readTape :: Tape -> Byte
readTape (Tape (ptr:xs) ys b) = ptr

-- is byte at ptr 0?
isZero :: Tape -> Bool
isZero = (==0) . readTape

isChar :: Char -> Tape -> Bool
isChar c = (==c) . chr . fromEnum . readTape

-- write to pointer position
writeTape :: Byte -> Tape -> Tape
writeTape n (Tape (ptr:xs) ys b) = Tape (n:xs) ys b

--increment, decrement the byte at ptr
increment :: Tape -> Tape
increment (Tape (ptr:xs) y b) = Tape ((ptr+1):xs) y b

decrement :: Tape -> Tape
decrement (Tape (ptr:xs) y b) = Tape ((ptr-1):xs) y b

inc = increment
dec = decrement

instance Show Tape where
  show (Tape (ptr:xs) ys b) = show (reverse xs) ++ " " ++ show ptr ++ " " ++ show (take (snd b - fst b) ys)

-- for the instruction tape
show' (Tape (x:xx) yy b) = reverse xs ++ " " ++ (ptr) ++ " " ++ take (snd b - fst b) ys
  where ptr = f x
        xs  = map f xx
        ys  = map f yy
        f   = chr . fromEnum

-- ============================================================================
-- Instruction Tape: reuse tape but add some functions

-- find matching ), assuming program is syntactically correct, i.e., there IS a matching ) AND the tape points to a ( 
-- same with ( and left, so parametrized. result points to the bracket, so this needs a right/left shift afterwards, like every other instr.
seekAny dir charMatch charOther t = go 0 (dir t)
  where go n t
          | n == 0 && isChar charMatch t = t
          | isChar charMatch t           = go (n - 1) (dir t)
          | isChar charOther t           = go (n + 1) (dir t)
          | otherwise                    = go n (dir t)

seekRight :: Tape -> Tape
seekRight = seekAny right ')' '('

seekLeft :: Tape -> Tape
seekLeft  = seekAny left  '(' ')'

-- init for instruction tape
initStringTape :: (Char) -> Tape
initStringTape = initTape . map (toEnum . ord)

-- the whole brainfuck program / machine is a turingmachine, where both tapes are in a state which can change with every instr.
data TM = TM {dataTape :: Tape, insTape :: Tape}

instance Show TM where
  show (TM d i) = "n" ++ show d ++ "n" ++ show' i

testtm = TM (initTape (2,7)) (initStringTape "(->+<)")
testtm2 = TM emptyTape (initStringTape "++++++++(>++++(>++>+++>+++>+<<<<-)>+>+>->>+(<)<-)>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.")

-- ============================================================================
-- Put the data into a stateful context using State (-transformers) 
-- ============================================================================

-- TM state transformers
newtype State s a = State {runState :: s -> (a, s)}

-- State data constructor proxy
state :: (s -> (a, s)) -> State s a
state = State

-- canonical stuff
instance Functor (State s) where
  fmap = liftM

instance Applicative (State s) where
  pure = return
  (<*>) = ap

instance Monad (State s) where
  return x = state (s -> (x, s)) 
  p >>= k = state $  s0 ->
    let (x, s1) = runState p s0
    in runState (k x) s1  

-- ============================================================================
-- The brainfuck operations are stateful
-- ============================================================================

-- let the monadic functions return effects. can be extended as necessary
data Effect = None | Result Byte

isNone None = True
isNone _    = False

-- these seem a bit verbose.. is this necessary? is there a better way?

-- shift data tape
fRight :: TM -> (Effect, TM)
fRight (TM d i) = (None , TM (right d) i)
sRight = state fRight

fLeft :: TM -> (Effect, TM)
fLeft (TM d i) = (None, TM (left d) i)
sLeft = state fLeft

-- increment byte at ptr on data tape
fInc :: TM -> (Effect, TM)
fInc (TM d i) = (None, TM (inc d) i)
sInc = state fInc

fDec :: TM -> (Effect, TM)
fDec (TM d i) = (None, TM (dec d) i)
sDec = state fDec

-- read or write byte from/to data tape
fOutp :: TM -> (Effect, TM)
fOutp tm = (Result (readTape $ dataTape tm), tm)
sOutp = state fOutp

fInp :: Byte -> TM -> (Effect, TM)
fInp byte (TM d i) = (None, TM (writeTape byte d) i)
sInp byte = state (fInp byte)

-- seek the next ( or the previous )
fFwd :: TM -> (Effect, TM)
fFwd (TM d i)
  | isZero d  = (None, TM d (seekRight i))
  | otherwise = (None, (TM d i))
sFwd = state fFwd

fBwd :: TM -> (Effect, TM)
fBwd (TM d i)
  | not $ isZero d = (None, TM d (seekLeft i))
  | otherwise = (None, (TM d i))
sBwd = state fBwd

-- ============================================================================

--read instruction from instr tape
fReadInstr :: TM -> (Byte, TM)
fReadInstr tm = (readTape $ insTape tm, tm)
sReadInstr = state fReadInstr

--next instruction: shift instr tape 
fNext :: TM -> ((), TM)
fNext (TM d i) = ((), TM d (right i))
sNext = state fNext

-- check if instruction tape is at the end
fCheck :: TM -> (Bool, TM)
fCheck (TM d i) = ((check i), TM d i)
  where check tape = (readTape tape) == 0
sCheck = state fCheck

sCheckNot = do 
  res <- sCheck
  return (not res)

-- ============================================================================
-- Putting it together: Run brainfuck turing machine step by step, 
-- collecting potential results (Effect)
-- ============================================================================

-- from Control.Monad.Loops
whileM :: Monad m => m Bool -> m a -> m (a)
whileM = whileM'

whileM' :: (Monad m, MonadPlus f) => m Bool -> m a -> m (f a)
whileM' p f = go
  where go = do
          x <- p
          if x
          then do
            x  <- f
            xs <- go
            return (return x `mplus` xs)
          else return mzero

-- from instruction character, resolve which action to take next.
chooseAction :: Enum a => a -> State TM Effect
chooseAction instr = 
  case chr . fromEnum $ instr of 
    '>' -> sRight
    '<' -> sLeft
    '+' -> sInc
    '-' -> sDec
    '.' -> sOutp --sOutp
    ',' -> return None --sInp -- to be combined with IO...
    '(' -> sFwd
    ')' -> sBwd
    _   -> return None

-- run the current step of the brainfuck program
stepTM :: State TM Effect
stepTM = do
  instr <- sReadInstr
  let next = chooseAction instr -- get statetransformer encoded by this char
  res <- next -- run that statetransformer
  sNext -- shift instruction tape pointer to right
  return res

-- combine a list of possibly empty effects into a string
combineEffects :: (Effect) -> (Char)
combineEffects ms = go "" ms 
  where
    go str () = str
    go str ((None):xs) = go str xs
    go str ((Result byte):xs) = go (str ++ ((chr . fromEnum $ byte))) xs

-- run a tm and print its result and states
runTM tm = (combineEffects (fst tup), (snd tup)) 
  where
    tup = runState (whileM sCheckNot stepTM) tm

Do any industry programming languages use Martin-Löf style identity types?

Most programming languages have some kind of type systems but are there any programming languages widely used outside of academia (in consumer-oriented tech, finance etc.) that have intensional identity types à la Martin-Löf?

Coq and Agda have identity types but they are primarily used in academia.

programming – Why create your own versions of tools when there are others out there?

Why would someone write their own network scanner with python when there are tools like nmap out there? In general, why would anyone write their own hacking tools if you can just grab one from github or something like that? Is it just for practicing programming or is there something I’m missing? As far as I know, I don’t think you can add any features to nmap but I’m sure that I’m wrong. I’ve heard that programming is very important for cyber security and one of the reasons for that is writing your own tools. Can someone explain this to me please?

Linear Programming Problems with decimal solutions for problems requiring whole number solution

I have an LPP which asks for the maximum number of pairs of shoes that can be manufactured to maximize the profit. The LPP is:


Maximize Z=1350x + 975y
Subject to, 3x+1.5y&leq;275
     2.5x+2y&leq;300
     x, y&geq;0

The solution I obtained is x=44.45; y=94.44
Now, since x and y can only be positive integers, what will the final solution be? I’m confused about this step. Any help is welcome :-]

customer management system for registering customers (in C programming language). Kindly provide feedback as well as corrections to be made

The prompt is: that I should write a program for a customer management system for registering customers (in C programming language).

The program should allow registration management members to:

  • Add customer record (id, name, age, gender and city) to the file.
  • Print customer details (ID, name, age, gender and city)

(Note: If the user enters the gender other than “male or female”, the program should display the error message “Invalid input! (gender must be male or female)” and enforce the user to enter the correct gender.)

#include <stdio.h>
#include<stdlib.h>
#include<string.h>

int n_r=0;
struct customer                                                                         // using a struct will be better than an array since it
{                                                                                       // can store several data types unlike an array
    int id;
    char firstname(20);
    char lastname(20);

    int age;
    char gender(6);
    char city(20);
};

void displayMainMenu()                                                                  // print menu
{
    printf("n -------------------------------------------------------------n");
    printf("n -------------Customer Management System ---------------------n");
    printf("n ------------------------* MAIN MENU *----------------------------n");
    printf("n |A/a:Enter A or a for Adding a Customer ");
    printf("n |D/d:Enter D or d for Printing Customer Details ");
    printf("n |E/e:Enter E or e for Exiting the Program |------------------n");
}  

char inputAndCheck()
{
    char ch;
    while(1)
    {
        displayMainMenu();
        printf("n Please enter your choice: ");
        scanf("%c",&ch);
        if(ch=='A'||ch=='a'||ch=='D'||ch=='d'||ch=='E'||ch=='e')
        break;
        else
        {
            printf("n > Invalid selection! Please try again ");
        }
    }
    return ch;
}
    

int readCustomerAge()
{
    int age;
    while(1)
    {
        printf("n Enter age: ");
        scanf("%d",&age);
        if(age>=15 && age<=90)

        break;
        else
        {
            printf("n > Invalid selection! (Age must be between 15 and 90) ");
        }
    }

    return age;
}                                                                       

int readCustomerGender()
{
    char ch1(6);
    while(1)
    {
        printf("n Enter gender: ");
        scanf("%s",ch1);
        if((strcmp(ch1,"male")==0)||(strcmp(ch1,"MALE")==0))
        {
            return 0;
        }
        else if((strcmp(ch1,"female")==0)||(strcmp(ch1,"FEMALE")==0))
        {
            return 1;
        }
        else{
            printf("n > Invalid selection! (Gender must be male or female) ");
        }
    }
}

char* readCustomerCity()
{
    char c(20);
    printf("n Enter city: ");
    scanf("%s",c);
    return c;
}

void displayCustomerDetails()
{
    FILE *fp;
    struct customer c;
    fp=fopen("customer.txt","r");
    if(fp==NULL)
    {
        printf("n Error in opening a file.");
        exit(1);
    }
    while(fread(&c,sizeof(struct customer),1,fp))
    printf("n Id:%d n Name:%s %s n Age=%d n Gender=%s n City=%s",c.id,c.firstname,c.lastname,c.age,c.gender,c.city);

    fclose(fp);
}

void addCustomerDetails()
{
    FILE *fp;
    struct customer c;
    char* gen;
    //char cit(30);
    if(n_r==0)
    {
        fp=fopen("customer.txt","w");
        if(fp==NULL)
        {
            printf("n Error in opening a file.");
            exit(1);
        }
    }
    else
    {
        fp=fopen("customer.txt","a");
        if(fp==NULL)
        {
            printf("n Error in opening a file.");
            exit(1);
        }
    }

    printf("n Enter customer ID: ");
    scanf("%d",&c.id);
    printf("n Enter customer first name: ");
    scanf("%s",&c.firstname);
    printf("n Enter customer last name: ");
    scanf("%s",&c.lastname);
    c.age=readCustomerAge();
    if(readCustomerGender())
    {
        strcpy(c.gender,"Female");
    }
    else
    {
        strcpy(c.gender,"Male");
    }

    printf("n Enter customer city: ");
    scanf("%s",&c.city);
    fwrite(&c,sizeof(struct customer),1,fp);
    fclose(fp); 
}

int main()
{
    int year;
    char ch;
    printf("n -------------------------------------------------------------n");
    printf("n -------------Welcome to Customer Management System ---------------------n");
    printf("n > Please Enter Customer registration year (ex:2017):");
    scanf("%d",&year);
    printf("n > How many customers do you want register in the year %d:",year);
    scanf("%d",&n_r);

    while(1)
    {
        ch=inputAndCheck();
        switch(ch)
        {
            case 'A':
            case 'a':
            addCustomerDetails();
            n_r++;
            break;

            case 'D':
            case 'd':
            displayCustomerDetails();
            break;
            
            case 'E':
            case 'e':
            printf("n > Thank you for using Customer Management System!n");
            printf("n > Good Bye. n");
            exit(0);
        }
    }

    return 0;
}

Please note, I still haven’t finished writing the comments for the program but will continue writing them after I receive feedback.