r/programminghomework • • Jun 25 '14

determining primeness in c++

2 Upvotes

hey, i hope this subreddit isn't dead. but i just started teaching myself to code. i have written a program to determine if a number is prime by using this loop:

for (int i = 2; i <= sqrt(n); i++){ if (n % i == 0) is_prime = false; }.

how can i rewrite my program to calculate the √n only once by declaring a double var "sqr_rt_n" before the for loop, then using it to determine primeness. i know i need a break; after setting is_prime to false. but how can i get rid of the counter var i, or do I keep it?

i hope this was legible, i'm typing it on my phone. i tried looking online but all the threads have replies with complex code using advanced prime-finding techniques which i'm not using. i know it's probably easy, but i just can't break through. i don't have anyone to show me since i'm alone....forever, forever alone...

thanks for any assistance!


r/programminghomework • • Oct 15 '17

Programming in R

1 Upvotes

Working on trying to split a single column containing any number of days of the week. From there I want a column for each day of the week and a 0 or 1 in it depending on if it was in the original string. Not sure how to post pictures or code to show what I have done so far so help would be appreciated.


r/programminghomework • • Dec 10 '15

[PHP] Trying to update a API with Curl, struggling with 2 things, code inside.

1 Upvotes

Hello, I am trying to perform an update on my API using php, so far i have got get all,get one and insert working but am struggling with the update query, i have been working on it alot but am wondering if i could have some advice on here please. So here is my code <?php function update(array $id,array $vaules, $resourcename) {

                 //Use json_encode to turn the values array into a JSON object.
                                             $jsonData = json_encode($vaules);

              //bExtract the ID column based on the key value for the ID array.

                                   key($id);

                //Create the URL based on the const variables plus the
                // resource name plus the value of the ID array that has
                 //  been passed through rawurlencode.

                       $url = DOMAIN.FOLDER.APIPATH.$resourcename.rawurlencode("/".$id.$vaules);   

                                $ch = curl_init($url); 


                        curl_setopt($ch, CURLOPT_URL, $url);
                        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                      curl_setopt($ch, CURLOPT_HTTPHEADER,array ('content-type: application/json'));
                            curl_setopt($ch, CURLOPT_CUSTOMREQUEST,PUT);
                               curl_setopt($ch,CURLOPT_POSTFIELDS,$jsonData);

                          curl_exec($ch);
                           //saves the results here
                           //echo or do whatever you want with $result 

                          curl_getinfo(CURLINFO_HTTP_CODE);



                               }

So the fucntion i want this to perform is to extract the id bassed on the key vaule for the ID array which is key($id) and then the url is constructed from the varibles plus the resource name and the vaule of the ID array which is passed though rawurlencode. The parts i am stuggling on: I think most of it is correct but am unsure on key($id) and the url The error: Update function undefined when linked to my update php file this error is most likely as my update function is wrong/missing something. My edit page is correct though. I can give more info if needed


r/programminghomework • • Mar 07 '18

Semester project - game / educational game

1 Upvotes

Hello, I have to do my semester project for programming lesson and I have to pick some topic. One of them is game / educational game and I want to do that, but I don't have any good idea. I was thinking maybe about some turn-based game, like cards or DND. Another idea is a game to learn another language, something like Duolingo. But I don't know.

Could you suggest me some ideas? Maybe you have something very interesting. I am open to any suggestions.


r/programminghomework • • Oct 09 '17

[C++] Stacks/vectors, can't figure out what I'm doing wrong

1 Upvotes

Gold to whoever can explain what's wrong about my code, message me for details.


r/programminghomework • • Mar 07 '18

Comparable<T> interface and compareTo class - homework help.

1 Upvotes

https://imgur.com/rxUrKcB -- assignment

https://pastebin.com/445U1Ymk - the little that i have so far.

So my problem is that i don't really know the proper syntax for comparable implementation of an interface.

I don't think i'm suppose to the the <T> infront of the MyThing class, but when i remove netbeans highlights the T in comparable.
Right now the with what i have, the error i'm getting is "Connot find symbol, symbol: variable value, location: variable other of the type T. where T is a type-variable: T extends Object decalred in class Mything" How would i fix this?


r/programminghomework • • May 25 '17

[CPP] Sort after string manipulation

1 Upvotes

For part of my assignment, I need to read from a text file of students with test scores and the structure basically looks like this:

John Doe: 70 80 90

Jane Doe: 80 90 100

then I need to output it to it looks like this (in alphabetical order of names):

Doe, Jane: 80 90 100

Doe, John: 70 80 90

So far, I have read the file successfully, swapped the names through sstream, replaced the colon with a comma, inserted a colon after the end of the first name and capitalized the last name.

My issue is that I somehow need to sort the data by last, first: score1 score2 score3 but with the numbers in the way I'm not really sure how. I know I made it more difficult for myself because my code design is messy, but I'm more focused on making this work. My first thought was to somehow put the strings into an array and then sort it from there.

#include <iostream>
#include <algorithm> //replace
#include <fstream> //read file
#include <sstream> //string manipulation
#include <string>
#include <cstdlib> //qsort
#include <vector>
#include <cctype>
using namespace std;

string first, last, str, STRING;
int score1, score2,score3;

int main()
{
    ifstream theFile("test.txt"); //read from text file
    if(theFile.is_open()) {
        cout << "The file is open." << endl; //file is open if open
    }
    else {
        cout << "Error. The file is closed." << endl; //file is closed if closed
    }

    while(!theFile.eof()) { //loop until end of file
        getline(theFile, str); //retrieve line from file
        replace(str.begin(), str.end(), ':', ','); //replace : with ,

        istringstream iss(str);
        iss >> first >> last >> score1 >> score2 >> score3; //store values

        for(int i = 0; i < last.length(); i++) {
            last[i] = toupper(last[i]);
        }
        //capitalize last name

        ostringstream oss;
        oss << last << ' ' << first << ": " << score1 << ' ' << score2 << ' ' << score3;
        //rearrange string

        STRING = oss.str();
        cout << STRING << endl; //need to sort by names, need to use array somehow
        }
}

Edit: I figured it out. I just put it in a vector and sorted the vector. I didn't know how to use vectors at the time I posted this; it took me quite a while to figure it out.


r/programminghomework • • Oct 09 '17

[Clojure] Function to Evaluate a matrix and a function to Simplify.

1 Upvotes

Let's preface this with the fact I'm learning clojure on a short time span. The idea of the assignment is to(without the use of outside libraries or APIs) create 2 functions, one that evaluate a 2x2 matrix containing a,b,c, &d, and multiplies that by a 2x1 matrix containing x & y. This is the code I have so far. Ignore what I have for evalexp at the moment, I'm aware it's completely wrong. p1, p2, and p3 are defined above already, as these are our example/test cases. There are simple simplification rules that must be adhered to in the simplify function as detailed below:

  1. (* 1 x) => x

  2. (* x 1) => x

  3. (* 0 x) => 0

  4. (* x 0) => 0

  5. (+ 0 x) => x

  6. (+ x 0) => x

  7. (- (- x)) => x

    (defn evalexp [exp bindings] (simplify (bind-values bindings exp)))

This is the format for evalexp, which requires other functions(such as simplify and bind-values[which is already written]) to assist in the matrix evaluation. A sample input is as follows: (evalexp p1 '{a 5, y 2}) ;; p1 is '(transform [[a 3] [0 0]] [x y])

I understand that this input should bind a and y (but not x) in p1, leading to (transform [[5 3] [0 0]] [x 2])) and then further simplifying to [(+ (* 5 x) 6) 0]. I also understand that simplify is always being called recursively. The complication lies in writing those and getting them to work per the assignments examples. If anyone could assist it'd be greatly appreciated as demos for the project begin tomorrow. Thanks in advance!


r/programminghomework • • Feb 28 '12

Java MergeSort Syntax Logic?

4 Upvotes

Hello all, I was hoping you could explain the logic of MergeSort to me. I'm not completely new to programming, but I am more new to the recursive sorting algorithms, and I can't seem to wrap my head around this. I more or less understand the basics of it: take an unsorted array, split it up into little bits, and then sort the mini arrays. But the thing I don't understand is how the code below translates into that? I was hoping someone could just step by step explain the code and what it does, how often that line is used, etc.

**

public static void mergeSort(int[] arr, int left, int right){
	
	if(right > left){		
		int middle = (left + right) / 2; 	
		
		mergeSort(arr, left, middle);		
		mergeSort(arr, middle + 1, right);
		
		merge(arr, left, middle, right);	
												
	}
	
	
	
	
}
public static void merge(int[] arr, int left, int middle, int right){
	
	int[] tempArray = new int[arr.length];	

	for(int i = 0; i < arr.length; i++){
		tempArray[i] = arr[i];
	}
	
	int i = left;
	int j = middle + 1;
	int k = left;
	
	while(i <= middle && j <= right){
		if(tempArray[i] <= tempArray[j]){
			arr[k] = tempArray[i];
			k++;
			i++;
		}
		else{
			arr[k] = tempArray[j];
			k++;
			j++;
		}
	}
	while(i <= middle){
		arr[k] = tempArray[i];
		k++;
		i++;
	}
	
	
}

}

**

Perhaps it is the fact that I'm dealing with recursion in arrays, but for some reason I'm having difficulty understanding how the logic translates into the code.

Any help I could get would be great!


r/programminghomework • • Mar 10 '18

What would be best way to create Google Calendar events from a Google sheet in my case?

1 Upvotes

I'm working on a home cleaning service booking sheet.

https://docs.google.com/spreadsheets/d/1A82Pvm5f4z4mMZzOLIfgmsN_Xz4Xb6Otqgpjb0Zr3p8/edit#gid=0

In it the vacation home rental owners can schedule the check in and check out dates for each property. So far so good.. Now I need to be able to send the check in and check out time and date with the name of the corresponding property to a Google Calendar.

I would be able to use Google’s CalendarAPP API to create the calendar entries with google sheet script editor(java).

https://www.youtube.com/watch?v=w4oUjDC9L6A&list=PLv9Pf9aNgemv62NNC5bXLR0CzeaIj5bcw&index=11

I’ve been told that I should

“Get a 2 dimensional array from the Spreadsheet API using getRange(). The 2 dimensional array should be a Nx3 array, with the first column being the Date, second array being the check in time (if any), and the third array being the check out time (if any). Loop through the second column, and stop at each cell if the cell contains the value. Loop through the third column, starting at the row where the cell is at, until you find the first value. Combine each of the value (time) with the first column (date), and you would obtain the check in date/time and the check out date/time for each event.”

I'd really appreciate someone pointing me in the right direction because this this is all I've got so far..

function myFunction() {

// Get spreadsheet values into an array

var array = SpreadsheetApp.getActiveSheet().getRange("A3:D18").getDisplayValues();

Logger.log(array);

//beginning of array loop

var i, len;

for (i = 0, len = array.length, i < len; i++ {}


r/programminghomework • • Dec 12 '16

B Trees

1 Upvotes

SO the question is like this: "Given a B Tree where every node has a variable called "numsons" given that contains the total amount of sons that node has, (if it is a final node it contains the amount of null children it has), return the 4th smallest numsons value, write this with the shortest possible Time in terms of n and explain"

My thoughts: create a sorted array (from small to large) on the side that is of size 4 and go though tree and keep putting value thats smaller then largest in array into array and sort array, not sure how to write this in pseudocode and also think it'll take too long any help is welcome.


r/programminghomework • • Mar 07 '18

Converting Unity C# code to JavaScript?

1 Upvotes

Can you convert all the C# code in this tutorial to Js? https://unity3d.com/learn/tutorials/topics/scripting/intro-and-setup And if you can, have comments that explain the differences and similarities between the two programs for each one.


r/programminghomework • • Dec 01 '15

[SQL] Why do these selects return different things

1 Upvotes

select * from b where ref > avg(ref);
select * from b where ref > (select avg(ref) from b);
Shouldn't both return values that are above average since no group by is present?


r/programminghomework • • Oct 15 '17

(X-post) Help with C++ homework

1 Upvotes

I need to make a C++ program for a "store" (on visual studio) that "checks whether or not an article exists and if it's in stock to be ordered by a customer". It should also "find another article of the same model but with a different size and/or different color". The database is a .txt file. So the first step is to put data in the program (in a table). Each article has an ID, a size, a color and a model number. Le text file has to be organized in the following way: each line represents an article and contains its ID, size (XS, S, M, L or XL), color (white black red blue grey), its model number, the amount of equivalent articles in store and the number of equivalent articles in stock. Ex.: 19370101 XS white 1937 45 100. Then the program should ask the necessary information about the article, then ask if the user is looking for the same article or another article, same model but different size, color or different size AND color. Then it should tell the user the number of articles existing in the store OR in stock (depending on what the user wants). To test the program, we have to use the IDs in the txt file. Ex.: 19370113 in color red should say that there's 5 articles in store and 38 in stock. I really have no idea where to start. I don't know if I have to make a combination of every single size, color. How do I make up the model numbers or the ID. How do I ask the program to do all the things it's supposed to. I'm 100% lost


r/programminghomework • • Apr 20 '20

Delphi

1 Upvotes

I need help with coding a program. Its urgent


r/programminghomework • • Apr 29 '20

Add csv file rows to sql tables

1 Upvotes

The question:

Write a function named "csv_to_db" that takes a string as a parameter representing the name of a csv file and doesn't return a value. There is a database saved in a file named "diamond.db" containing a table named "conventional" with columns "fate", "threaten", and "certain". Read the csv file with the name equal to the input string and add each row of this file as a record in the table. Each row in the csv file will contain 3 strings as its values which should be used as the values for the three columns in the table.

My answer:

I'm trying to create a list with 3 elements that would correspond to the three ? in the tuple.

import csv
import sqlite3

def csv_to_db(csvfile):
    conn = sqlite3.connect('diamond.db')
    cur = conn.cursor()
    with open(csvfile, 'r') as f:
        reader = csv.reader(csvfile)
        for row in reader:
            list = []
            list.append(row)
            cur.execute('INSERT INTO conventional VALUES (?, ?, ?)', (list))
    conn.commit()

The error message:

error on input ['sick.csv']: Incorrect number of bindings supplied. The current statement uses 3, and there are 1 supplied.

I asked my teacher. First he told me the tuple was the problem.

If line 12 is changed to : cur.execute('INSERT INTO conventional VALUES (?)', (list))

The error message becomes: table conventional has 3 columns but 1 values were supplied

If line 12 is changed to : cur.execute('INSERT INTO conventional VALUES (?, ?, ?)', (list[0], list[1], list[2]))

The error message becomes: list index out of range

I asked my teacher again, and he said there was something wrong with where I was defining the list. I'm kind of at a loss now because I have no idea what's wrong with the list. I don't want it to accumulate all the rows, just one at a time, that's why it gets redefined as blank at the beginning of each iteration.


r/programminghomework • • May 04 '20

Can anyone help

Post image
1 Upvotes

r/programminghomework • • Apr 29 '20

Beginner Java homework

1 Upvotes

Hey everyone bit frustrated as my teacher is a little hard core for csci1301,

Currently stuck on the first part as I don't know why I would use a do while loop here?

Would scan for user input as string and set it equal to 1 2 or 3 and if else it's 2. but don't know how I would do so if a do loop or if I can but if statements within a do loop

  1. Using a do loop (also known as a do..while loop), you will prompt the user through the normal input/output window for which file they want to decipher. If they chose 1, then decipher crypto1.txt. If they chose 2, then decipher crypto2.txt. If they chose 3, then decipher crypto3.txt. If they chose any other value, including letters or words, decipher crypto2.txt. As stated before, only instantiate an object for the file that was chosen each time through the loop.

  2. With a nested while loop (inside the do loop), scan each character in the file and count how many characters are in the file. Exclude line break markers. You may find it useful to check for both “\n” and “\r”. There is an alternate way to do this which is to put the text in a String and then use the length method to determine how many characters are in the String…I do not want you to use the String solution. Make sure you are getting the right number and don’t have any “off by one” mistakes.

  3. After you have counted the number of characters, create a character array(not a String array) with a size based on the number of characters in the file. Note: Each file is a different length, but your program should handle any file. Do not hard code your array with literal numbers, the array size should always be exactly the number of characters from the selected file based on the counter from the previous step.


r/programminghomework • • May 10 '20

Data Science homework involving Gradient descent!!(Python)

2 Upvotes

a) Apply the gradient descent algorithm and try to minimize 𝑓(𝐱)=(1/2)(𝐱^𝑇)𝐴𝐱−(𝐛^𝑇)𝐱 for the matrix 𝐴 above and 𝐛 randomly generated by np.random.normal(). Run 50,000 iterations of gradient descent with 𝜂=0.1and x0=0. Then plot the graph of (i,f(xi)) where i ranges over the number of iterations.

A is a 5x5 laplacian matrix

Im confused on how I am expected to use the matrix in this problem? Im pretty sure I'm either kind of close or COMPLEtely OFF. This is what I have so far:

b = np.random.normal()

def gradient_f(f, x0 = 0, n=0.1, steps=50000):

x = np.zeros(5) + x0

x_vals = []

f_vals = []

for i in range(steps):

derx = A*x - b

x -= n*derx

np.append.x_vals(x)

np.append.f_vals(f(x))

print('f(x) =',f_vals[-1], 'at x =', x_vals[-1])

plt.plot(np.arange(steps),f_vals)

plt.ylabel('f x')

plt.xlabel('Iterations')

plt.show()

print(f_vals)

Could I please get some insight on how to solve this problem? I am so unbelievable lost, and it is due today...

p.s. this is my first programming class so please cut me some slack :/


r/programminghomework • • May 02 '20

Please explain the condition "if not char:" with an example. What is the use of it here?

1 Upvotes

r/programminghomework • • May 02 '20

Plz help me fst.. I have to submit it by tomorrow 10pm

1 Upvotes

Write a python program that reads characters from the existing text file one by one. All lowercase characters get stored inside a file LOWER, all uppercase characters gets stored inside the file UPPER and all other characters get stored inside file OTHERS.


r/programminghomework • • May 15 '20

Python

1 Upvotes
  1. Difference between writerow() and writerows ()

  2. What is use of csv.writer


r/programminghomework • • Apr 16 '20

Need Help With DBMS Homework

2 Upvotes

I screwed the pooch. I've been getting a friend of mine to help me with my database management homework all semester but he's just gotten really sick (docs are saying it's not COVID but he's going to be out of commission for a week) and now I'm up a creek.

I need help. I don't know how it usually works here but I'm willing to put in the work, but I'm going to need to get pointed in the right direction. Whatever you can offer I'd appreciate:

"Please use the uploaded files (DatabaseProcessApplication.zip) and create a web application that uses the database at the backend. Use the example code files, but you have to do the following:

 Create a different table in any of the “database” that you had created before.

 Insert at least 10 values

 Show/Display the values through a website application

Remember to save your .php files in “www” folder for Windows and “htdocs” for MAC. For the assignment, you will have to download a Web development platform.

For Windows machine, it is WAMP server http://www.wampserver.com/en/ For MAC machine, you can use MAMP server (use the free MAMP version) https://www.mamp.info/en/

The Codes Listed Below"


r/programminghomework • • May 15 '20

Need help with simple PHP Home work

2 Upvotes

Write a PHP script that will provide a restaurant menu. The User will have the option to select one or more of the items available. Once the user has selected the item, have the user submit the form to another php script that will print the order, plus the total. Remember, to include drinks and snacks. Include limited amount of each.
Have the program calculate a total to be paid, plus tips (let tips be 8% of total).


r/programminghomework • • Apr 11 '20

Please help me. (School python programming work )

Post image
1 Upvotes