CS50, vigenere.c lack of argv - argv

I tried check50, and I got some message for the command down below.
#include<cs50.h>
#include<stdio.h>
#include<ctype.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
int main(int argc, string argv[])
{
string a = argv[1];
int s = strlen(a);
if(s == 0)
{
printf("No keyword entered\n");
return 1;
}
for(int k = 0; k < s; k++)
{
if(!isalpha(a[k]))
{
printf("keyword not alphabetical\n");
return 1;
}
}
string t = GetString();
int i = 0;
int x = 0;
int v = 65;
for(int n = strlen(t); i < n; i ++)
{
if(isalpha(t[i]))
{
if(isupper(t[i]))
{
if(isupper(t[i]))
{
if(islower(a[x]))
{
v = v + 32;
}
int p = a[x];
p = p -v;
int 1 =t[i];
1 = 1 - 65;
int b = (1+ p[s%x]%26;
b = b + 65;
char c = b;
printf("%c", c);
x = x+1;
}
if(islower(t[i]))
{
int p = a[x];
p = p - v;
int 1 = t[i];
1 = 1-97;
int b =(1 +p[s%x]%26;
b = b + 97;
char c = b;
printf("%c", c);
x = x + 1;
}
}
else
{
printf)"%c", t[i]);
}
}
printf('\n');
}
Error message:
:| encrypts "a" as "a" using "a" as keyword
:| encrypts "world, say hello!" as "xoqmd, rby gflkp!" using "baz" as keyword
:| encrypts "BaRFoo" as "CaQGon" using "BaZ" as keyword
:| encrypts "BARFOO" as "CAQGON" using "BAZ" as keyword
:| handles lack of argv[1]
:| handles argc > 2
:| rejects "Hax0r2" as keyword
How to fix it all?

Related

Java Code to Haskell (Problems with 2D and 3D arrays)

I have been asked to translate the following code which finds a maximum non-overlapping increasing sub sequence given a large amount of input. I haven't had much time to learn a lot on Haskell and I am stuck how to actually do it.
Here is the code in Java:
import java.util.*;
public class mnois {
public static int[][] memo;
public static int[][] lis;
public static int[] nums;
public static int[][][] lmemo;
public static int n;
public static String input;
public static String[] arrIn;
public static void main(String[] args) {
Scanner br = new Scanner(System.in);
int t = br.nextInt();
for(int c = 1;c<=t;c++) {
n = br.nextInt();
input = br.nextLine();
arrIn = input.split(" ");
nums = new int[n];
for(int i = 0;i<n;i++){
nums[i] = Integer.parseInt(arrIn[i]);
}
memo = new int[n][n+1];
for(int i = 0;i<n;i++){
Arrays.fill(memo[i], -1);
}
lmemo = new int[n][n+1][n+1];
for(int i = 0;i<n;i++){
for(int j = 0;j<n+1;j++){
Arrays.fill(lmemo[i][j], -1);
}
}
lis = new int[n][n];
for(int i = 0;i<n;i++){
for(int j = i;j<n;j++){
lis[i][j] = lis(i, n, j);
}
}
for(int i = 1;i<=n;i++){
System.out.print(go(0, i));
if (i != n){
System.out.print(" ");
}
}
System.out.println();
}
}
public static int lis(int pos, int last, int max) {
if (pos > max) {
return 0;
}
if (lmemo[pos][last][max] != -1){
return lmemo[pos][last][max];
}
int best = lis(pos+1, last, max);
if (last == n || nums[pos] > nums[last]) {
best = Math.max(best, lis(pos+1, pos, max)+1);
}
return lmemo[pos][last][max] = best;
}
public static int go(int pos , int k){
if (pos >= n) {
return 0;
}
if (memo[pos][k] != -1){
return memo[pos][k];
}
int best = go(pos+1, k);
for(int i = pos;i<n;i++){
if (lis[pos][i] >= k) {
best = Math.max(best, go(i+1, k)+lis[pos][i]);
}
}
return memo[pos][k] = best;
}
}
I am particularly having problems with creating mutable 2D and 3D arrays. Appreciate any help I can get.
This is what I have so far:
import Data.Array.IO
case :: Int -> Int -> Bool
case index n =
if (index >= n)
return True
else do
numElems :: Int <- readLn
strElems <- readLn
nums <- newArray_ (0, numElems) :: Int
addElems nums 0 0 numElems strElems
memo <- newArray ((0, 0), (strElems, strElems+1)) -1 :: IO (IOArray (Int, Int) Int)
lmemo <- newArray (((0,0),(0,0)), ()) -1 :: IO (IOArray (Int, Int) IO (IOArray (Int, Int) Int))
lis <- newArray ((0, 0), (strElems, strElems)) -1 :: IO (IOArray (Int, Int) Int)
addElems :: (IOArray s Int Int) -> Int -> Int -> Int -> String -> IO s ()
addElems arr startArr strIndex finish string =
if (start >= finish) then
return ()
else do
num <- digitToInt $ string !! strIndex
writeArray arr startArr char
addElems arr (startArr+1) (strIndex+2) finish string
lisLoop :: (IOArray s Int Int) -> Int -> Int -> IO s ()
listLoop arr start finish =
if (start >= finish) then
return ()
else do
next 0 finish
where
next i currIdx len =
if (i < len)
writeArray arr (currIdx, i)
next (i+1) currIdx len

How can I bind the given input to another proctype function?

I need some help according to follow problem which I have to implemented it using jSpin and promela language.
A home alarm system can be activated and deactivated using a personal
ID key or password, after activation the system enters a waiting
period of about 30 seconds, time that allows users to evacuate the
secured area after which the alarm is armed, also when an intrusion is
detected the alarm has a built in waiting period or delay of 15
seconds to allow the intruder to enter the password or swipe the card
key thus identifying himself, in case that the identification is not
made within the allocated 15 seconds the alarm will go off and will
be on until an id card or password is used to deactivate it.
Here is what I tried:
mtype = {sigact, sigdeact};
chan signal = [0] of {mtype};
chan password = [0] of { int };
/*chan syntax for declaring and initializing message passing channels*/
int count;
bool alarm_off = true; /*The initial state of the alarm is off*/
active proctype alarm()
{
off:
if
:: count >= 30 -> atomic {signal!sigdeact; count = 0;alarm_off = false; goto on;}
:: else -> atomic {count++; alarm_off = true; goto off;}
fi;
on:
if
:: count >=15 -> atomic { signal!sigact; count = 0;
alarm_off = false; goto off;}
:: else -> atomic {signal!sigact; alarm_off = true; goto pending;}
fi;
pending:
if
:: count >= 30 -> atomic {count = 0; alarm_off = false; goto on;}
:: count < 30 -> atomic {count++; alarm_off = false; goto pending;}
fi;
}
active proctype user()
{
password ! 1234 //1234 is the password I sent.
input: atomic { signal?sigact -> alarm_off = true; goto off; }
}
In the user proctype I send the password
password ! 1234
How can I verify if the password is 1234 and how can I adapt it to own cases ( on, off , pending) based on the verification ?
As the code in the example doesn't appear to follow the specification, at least in the way I understand it, I wrote an example from scratch.
Please note that the following model (source code) is purposely very verbose and redundant in its structure, so that its easier to recognise its logic blocks and --hopefully-- understand it. In practice, one would use some inline function to handle input. I also didn't use SIGACT, SIGDEACT which appeared in the original model, since I could not figure out who was supposed to read those messages neither from the original model (source code) nor from the specification.
#define ALARM_OFF 1
#define ALARM_COUNTDOWN 2
#define ALARM_ARMED 4
#define ALARM_INTRUSION 8
#define ALARM_FIRED 16
#define INPUT_SET_PASSWORD 1
#define INPUT_CHECK_PASSWORD 2
#define INPUT_INTRUDER 4
mtype = { SIGACT, SIGDEACT };
init {
chan alarm_out = [1] of { mtype };
chan alarm_in = [1] of { byte, short };
run alarm(alarm_in, alarm_out);
run user(alarm_in);
run event(alarm_in);
}
proctype alarm(chan input, output)
{
byte count;
byte state = ALARM_OFF;
short passwd = 1234;
short tmp = 0;
off:
if
:: nempty(input) ->
if
:: input?INPUT_SET_PASSWORD(tmp) ->
passwd = tmp;
:: input?INPUT_CHECK_PASSWORD(tmp) ->
if
:: tmp == passwd ->
atomic {
state = ALARM_COUNTDOWN;
count = 0;
goto countdown;
}
:: else ->
skip;
fi;
:: input?INPUT_INTRUDER(tmp) ->
skip;
fi;
:: empty(input) -> skip;
fi;
goto off;
countdown:
if
:: count < 30 ->
if
:: nempty(input) ->
if
:: input?INPUT_SET_PASSWORD(tmp) ->
skip; // error: cannot be done now (?)
:: input?INPUT_CHECK_PASSWORD(tmp) ->
if
:: tmp == passwd ->
atomic {
state = ALARM_OFF;
count = 0;
goto off;
}
:: else ->
skip; // error: incorrect password (?)
fi;
:: input?INPUT_INTRUDER(tmp) ->
skip;
fi;
:: empty(input) ->
skip;
fi;
:: else ->
atomic {
state = ALARM_ARMED;
count = 0;
goto armed;
}
fi;
count++;
goto countdown;
armed:
if
:: nempty(input) ->
if
:: input?INPUT_SET_PASSWORD(tmp) ->
skip; // error: cannot be done now (?)
:: input?INPUT_CHECK_PASSWORD(tmp) ->
if
:: tmp == passwd ->
atomic {
state = ALARM_OFF;
count = 0;
goto off;
}
:: else ->
skip; // error: incorrect password (?)
// maybe it should be handled like
// INPUT_INTRUDER(tmp)
fi;
:: input?INPUT_INTRUDER(tmp) ->
atomic {
state = ALARM_INTRUSION;
count = 0;
goto intruder_detected;
}
fi;
:: empty(input) ->
skip;
fi;
goto armed;
intruder_detected:
if
:: count < 15 ->
if
:: nempty(input) ->
if
:: input?INPUT_SET_PASSWORD(tmp) ->
skip; // error: cannot be done now (?)
:: input?INPUT_CHECK_PASSWORD(tmp);
if
:: tmp == passwd ->
atomic {
state = ALARM_ARMED;
count = 0;
goto armed;
}
:: else ->
skip; // error: incorrect password (?)
fi;
:: input?INPUT_INTRUDER(tmp) ->
skip;
fi;
:: empty(input) ->
skip;
fi;
:: count >= 15 ->
atomic {
state = ALARM_FIRED;
count = 0;
goto alarm_fired;
}
fi;
count++;
goto intruder_detected;
alarm_fired:
if
:: nempty(input) ->
if
:: input?INPUT_SET_PASSWORD(tmp) ->
skip; // error: cannot be done now (?)
:: input?INPUT_CHECK_PASSWORD(tmp);
if
:: tmp == passwd ->
atomic {
state = ALARM_OFF;
count = 0;
goto off;
}
:: else ->
skip; // error: incorrect password (?)
// warn user but keep alarm on
fi;
:: input?INPUT_INTRUDER(tmp) ->
skip;
fi;
:: empty(input) ->
skip;
fi;
goto alarm_fired;
};
proctype user(chan output)
{
output ! INPUT_CHECK_PASSWORD(1234);
};
proctype event(chan output)
{
output ! INPUT_INTRUDER(0);
};
So, basically you have to check both the input (if any!) and the value of count in order to perform a transition in the internal FSM of the alarm system.
In the example I added a proctype of name event which will randomly send a single INPUT_INTRUDER input signal to the alarm system. This, in combination with the user typing his own password, can be used to trigger the chain of events which would cause the alarm to fire.

Increasing Intensity when converting HSI to RGB in OpenCV using C++

Updating the question I am asking. I have successfully been able to convert from RGB to HSI and back again. I was given instruction by my professor to also increase the image intensity by adding ((1.0 - I) / 2.0) to I (intensity) before I output the image. When I do this it appear to be causing overflowing, hence all my checks for RGB, etc. If I subtract the above formula, it successfully darkens the image without the overflow issues. I can't seem to identify the cause of this overflow nor know how to correct it. I at first thought that it was related to values where R = G = B, but I have confirmed by outputting these variables and debugging that this isn't the case. What causes it is when the saturation, S, is equal to zero. When S = 0, I know that hue, H, is irrelevant. Any assistance would be greatly appreciated!
#include<opencv2/core/core.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>
#include<iostream>
#define M_PI (3.14159265358979323846)
using namespace cv;
int main(int argc, char * argv[])
{
if (argc <= 1)
{
std::cerr << "Not enough arguments." << std::endl;
return (1);
}
Mat img = cv::imread(argv[1], CV_LOAD_IMAGE_COLOR);
std::cout << img.channels() << std::endl;
if (img.empty())
{
std::cerr << "Unable to open the image " << argv[1] << "." << std::endl;
return (1);
}
namedWindow("Original Image", CV_WINDOW_AUTOSIZE);
imshow("Original Image", img);
Mat hsi(img.rows, img.cols, img.type());
Mat newBGRimg = Mat::zeros(img.rows, img.cols, img.type());
double B, G, R, H, S, I, b, g, re;
int intB = 0, intG = 0, intR = 0;
for (int r = 0; r < img.rows; r++)
{
for (int c = 0; c < img.cols; c++)
{
b = img.at<Vec3b>(r, c)[0];
g = img.at<Vec3b>(r, c)[1];
re = img.at<Vec3b>(r, c)[2];
// Normalize colors
B = b / 255;
G = g / 255;
R = re / 255;
// BGR to HSI
double theta = acos((((R - G) + (R - B)) / 2) / (sqrt((pow((R - G), 2)) + ((R - B)*(G - B) + 0.0001))));
if (B <= G)
{
H = theta;
}
if (B > G)
{
H = (2 * M_PI) - theta;
}
if (H < 0)
H = 0;
if (H > 2 * M_PI)
H = 2 * M_PI;
double min = std::min({ B, G, R });
S = 1 - (3 * min) / (B + G + R); // / (B + G + R)
if (S < 0)
S = 0;
if (S > 1)
S = 1;
I = (B + G + R) / 3;
I = I + ((1.0 - I) / 2.0);
if (I < 0)
I = 0;
if (I > 1)
I = 1;
// HSI to BGR
if (H >= 0 && H < (2 * M_PI / 3))
{
B = I * (1 - S);
R = I * (1 + ((S * cos(H)) / (cos((M_PI / 3) - H))));
G = (3 * I) - (R + B);
B *= 255;
G *= 255;
R *= 255;
if (B > 255)
B = 255;
if (G > 255)
G = 255;
if (R > 255)
R = 255;
if (B < 0)
B = 0;
if (G < 0)
G = 0;
if (R < 0)
R = 0;
intB = (int)round(B);
intG = (int)round(G);
intR = (int)round(R);
//std::cout << intB << " " << intG << " " << intG << " " << r << " " << c << std::endl;
newBGRimg.at<Vec3b>(r, c)[0] = intB;
newBGRimg.at<Vec3b>(r, c)[1] = intG;
newBGRimg.at<Vec3b>(r, c)[2] = intR;
}
else if (H >= (2 * M_PI / 3) && H < (4 * M_PI / 3))
{
H = H - (2 * M_PI) / 3;
R = I * (1 - S);
G = I * (1 + ((S * cos(H)) / (cos((M_PI / 3) - H))));
B = (3 * I) - (R + G);
B *= 255;
G *= 255;
R *= 255;
if (B > 255)
B = 255;
if (G > 255)
G = 255;
if (R > 255)
R = 255;
if (B < 0)
B = 0;
if (G < 0)
G = 0;
if (R < 0)
R = 0;
intB = (int)round(B);
intG = (int)round(G);
intR = (int)round(R);
newBGRimg.at<Vec3b>(r, c)[0] = intB;
newBGRimg.at<Vec3b>(r, c)[1] = intG;
newBGRimg.at<Vec3b>(r, c)[2] = intR;
}
else if (H >= (4 * M_PI / 3))
{
H = H - (4 * M_PI) / 3;
G = I * (1 - S);
B = I * (1 + ((S * cos(H)) / (cos((M_PI / 3 - H)))));
R = (3 * I) - (G + B);
B *= 255;
G *= 255;
R *= 255;
if (B > 255)
B = 255;
if (G > 255)
G = 255;
if (R > 255)
R = 255;
if (B < 0)
B = 0;
if (G < 0)
G = 0;
if (R < 0)
R = 0;
intB = (int)round(B);
intG = (int)round(G);
intR = (int)round(R);
newBGRimg.at<Vec3b>(r, c)[0] = intB;
newBGRimg.at<Vec3b>(r, c)[1] = intG;
newBGRimg.at<Vec3b>(r, c)[2] = intR;
}
}
}
namedWindow("New RGB Image", CV_WINDOW_AUTOSIZE);
imshow("New RGB Image", newBGRimg);
imwrite("hsi-to-rgb.jpg", newBGRimg);
waitKey(0);
return 0;
}
In my original code I was trying to normalize the BGR values using for ex. B/B+G+R per DI 3rd edition supplemental material. . This should have been B/255 to normalize that to [0,1]. I believe the book was incorrect in suggesting this normalization method.

Printing intermediate value in recursive function in Haskell

I am new to Haskel and want to learn it. I want to print intermediate value in recursive function in haskell but i am stuck in parse error on input "=" on line b= b+50.
`main' t s a b c
| t > s = 0
| otherwise = do
print a
print b
print c
b = b + 50
c = b + 2 * a
main' (t+1) s (a+1) b c `
the C equivalent for this code is
int calculate(t,s,a,b,c)
{
printf( "%d,%d,%d",a,b,c);
if(t > s)
return 0;
else
{
b = b + 50;
c = b + 2 * a;
return calculate (t+1,s,a,b,c);
}
}
int main()
{
calculate(0,10,2,6,7);
return 0;
}`
Please help me to resolve this problem. It is not so difficult to do in C but I could not figure out how to do it in Haskel.
As PyRulez says in his comment, you need to use let syntax in do blocks. However, you are also going to run into issues because your function parameters, like all values in Haskell, are immutable. You will need to do something like:
let b' = b + 5
let c' = b' + 2 * a
If you only want to print some intermediate value, you don't need to have your function in the IO world:
you can use the Debug.Trace module:
import Debug.Trace
func :: Int -> Int -> Int -> Int -> Int
func 0 _ _ _ = 0
func t a b c = trace ("a="++(show a)++" b="++(show b)++" c="++(show c)) $ recurs
where recurs = func (t-1) (a+1) (b+50) (b+2*a)
it gives me:
> func 5 1 1 1
a=1 b=1 c=1
a=2 b=51 c=3
a=3 b=101 c=55
a=4 b=151 c=107
a=5 b=201 c=159

Translate Excel formula into structured english

I have this formula, with the variables, m,s and e.
IFERROR(IF(m - IF(s*(1/ABS(e))>m;m;s*(1/ABS(e)))>m;m;m-IF(s*(1/ABS(e))>m;m;s*(1/ABS(e))))/100;0)
I want to translate it to structured english, this is what I have, but I doubt its correct:
IF e != 0
IF m > m
return m
ELSE IF s / |e| > m
return m
ELSE IF s / e > m
return m - s / e
ELSE
return s / e
ELSE
return 0
?? forgot this one upss.. s / e / 100;
After analyzing the function, I think this simplified version has the same result:
=IFERROR(IF(MIN(m;s/ABS(e))<0;m;m-MIN(m;s/ABS(e)))/100;0)
And its logic can be explained like this:
if e = 0
0
else if m - (min between s/|e| and m) > m
m
else
m - (min between s/|e| and m)
Even still, I don't understand what that is for. :P
Edit: I added a simplified Javascript version of Sir Ben's code:
function whacko (m,s,e) {
if (e === 0)
return 0;
var value = m - Math.min(s / Math.abs(e), m);
if (value > m)
return m;
return value;
};
Thanks to Andrew's great reply, this is the working code in JS:
var m = 33
, s = 43
, e = 12.75; // Excel: 29,6%
function whacko (m,s,e) {
if (e === 0) {
return 0;
} else if (m - (Math.min(s/Math.abs(e), m)) > m) {
return m;
} else {
return m - (Math.min(s/Math.abs(e), m));
}
};
console.log(whacko(m,s,e)); // 29.627450980392158

Resources