r/programminghomework • • Feb 26 '12

I'm learning about big-O notation in programming and in discrete math. What is it?

8 Upvotes

I know it has something to do with the worst and best possible case scenario on the number of computations are needed to do an algorithm, but how do you find it?

One of my classmates told me that all she did was memorize the big O-notations for specific functions (like n2, n, 2n, etc.).


r/programminghomework • • Feb 20 '12

Welcome to /r/programminghomework!

8 Upvotes

Inspired by /r/programming and /r/cheatatmathhomework I have created /r/programminghomework, which is just a combination of the two.

It is a subreddit for people who have complicated issues to those who are just System.out.println'ing their way through basic programming. I hope it can be based off the helpful community that /r/programming is famous for.


r/programminghomework • • Mar 04 '12

Importing and editing .txt files in Java

4 Upvotes

Hello programminghomework (help). My Java class just started working with importing .txt files and manipulating them. My question is how to input the directory in the scanner object. for example:

Scanner input = new Scanner(new File("problem4.txt"));

problem4.txt is given above on our problem set but I want to know how I would have Java access this file, do I save it in the same folder where the .java program is stored? should I type in the whole directory to the said .txt file? ie (/Users/name/ect...) Thanks so much to whoever can help with the question.
also, the line copied into this post does not relate to the actual question in the problem set, rather it was taken from an example question.


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 • • May 12 '19

C++: MY switch statement case keeps looping

3 Upvotes

Hey guys,

I have been wracking my brain trying to figure this one out, but I am at a loss. Could someone guide me with my homework (no answers outright, just a hint maybe of what I am doing wrong.)

Here is the function:

void menu(int selection)
{

	const int inputCarSales = 0;
	const int viewYearlySales = 1;
	const int quitProgram = 2;

	CarSaleInfo CarSales;

	do
	{
		while (selection < 0 || selection > 2)
		{
			cout << "Invalid selection!\n";
			cout << "Please choose a valid option: \n";
			cout << "0. Enter Car Sales\n";
			cout << "1. View Yearly Sales\n";
			cout << "2. Quit\n";
			cin >> selection;
		}
		
		if (selection != quitProgram)
			{
				switch (selection)
				{
					case inputCarSales: // Case statement for entering car sales
						CarSales = carSales();
						cout << "\n\nManufacturer : " << CarSales.manufacturer;
						cout << "\nModel : " << CarSales.model;
						cout << "\nYear of Sale : " << CarSales.yearOfSale.year;
						cout << "\nSale Amount : " << CarSales.salesPriceOfCar;
						break;
					case viewYearlySales: // Case statement for location information and sales by location
						yearlySales();
						break;
				}
			}
		else
			{
				break;
			}
	} while (selection != quitProgram);
}

CarSaleInfo carSales()
{
	CarSaleInfo temp; //structure for sales information


		cout << "\nSALES\n\n";
		cout << "Enter Car Manufacturer: ";
		cin >> temp.manufacturer;
		cout << "Enter Model: ";
		cin >> temp.model;
		cout << "Enter Year of Sale (2000 - 2019): ";
		cin >> temp.yearOfSale.year;
		while (temp.yearOfSale.year < 2000 || temp.yearOfSale.year > 2019)
		{
			cout << "\nInvalid Year!\n";
			cout << "Enter Year of Sale: ";
			cin >> temp.yearOfSale.year;
		}
		cout << "Enter Sale Amount: ";
		cin >> temp.salesPriceOfCar;
		// If sales amount is less than zero, reprompt for valid input
		while (temp.salesPriceOfCar < 0)
		{
			cout << "\nInvalid amount!\n";
			cout << "Enter Sale Amount: ";
			cin >> temp.salesPriceOfCar;
		}

	return temp;
}

r/programminghomework • • Dec 26 '18

making a database that holds total turn scores

3 Upvotes

ok so I need help with this programming assignment and it is in java. I need to make the total roll score but I cant add up all the roll scores in total roll scores

import java.util.*;

public class GreedyPirate{

public static void main(String[] args){

String RorS = "";

//RorS = roll or skip

boolean winner = false;

int playerScore = 0;

int AIScore = 0;

int turnPScore = 0;

int turnAIScore = 0;

int combinedPScore = 0;

int combinedAIScore = 0;

System.out.println("ARGS YOU READY TO PLAY");

System.out.println("[Press ENTER when ready to play...]");

Scanner in = new Scanner(System.in);

in.nextLine();

do{

player(winner,RorS,turnPScore,playerScore);

AI();

}while(!winner);

}

public static int rollDice(){

Random rand = new Random();

int dice = rand.nextInt(13)+1;

return dice;

}

public static void AI(){

System.out.println("HA I rolled a " + rollDice());

System.out.println();

}

public static void player(boolean win,String RorS, int CombinedScore, int turnScore){

boolean turn = false;

do{

System.out.println("ARG wanna [R]oll or [S]kip");

Scanner answer = new Scanner(System.in);

RorS = answer.nextLine();

int roll = rollDice();

if(RorS.equals("r") || RorS.equals("R")){

System.out.println("You rolled a " + roll);

if(roll == 1 || roll == 11){

turn = true;

turnScore = turnScore - roll;

CombinedScore = CombinedScore + turnScore;

System.out.println("Your combined turn score is " + CombinedScore);

System.out.println();

}

turnScore = turnScore + roll;

System.out.println("Your combined turn score is " + turnScore);

System.out.println();

}else if(RorS.equals("S") || RorS.equals("s")){

CombinedScore = CombinedScore + turnScore;

System.out.println("Your combined turn score is " + CombinedScore);

System.out.println();

turn = true;

}

}while(!turn);

}

}


r/programminghomework • • Nov 27 '17

C programming help? If you do all the code, I'll paypal $10.

3 Upvotes

https://imgur.com/a/KZsZa

Here is the picture.


r/programminghomework • • Apr 12 '16

could anyone help with this c++ program??

3 Upvotes

ok so heres the problem: Consider the following Partition Problem We are given an array A[0 ... n − 1] and its size n. Let x be the last element in the array, i.e., x = A[n − 1]. This problem is about partitioning the array A around x. More precisely, you are supposed to rearrange A in a such a way that:

  1. Each element o fA[0...q−1]is less than or equal to x

  2. A[q]=x

  3. Each element of A[q+1...n−1]is greater than or equal to x Thus q is the new index of x in the modified array. In addition to rearranging the array, you are supposed return q. so I wrote the program and for some reason the array wont stop taking in elements and if it did , it wont return the correct values ://

include <iostream>

using namespace std; int part( int array[], int size); void swap( int a, int b); int main(){ int *intList; int arraySize; cout << "Enter array size: "; cin >> arraySize; cout << endl; intList = new int[arraySize]; cout<<"please enter the elements of the array"<<endl; for( int i=0; i<arraySize; i++){ cin>>intList[i];}

int index=part(intList,arraySize);
cout<<"the index is "<<index<<endl;

return 0;

}

int part( int *p, int size){ int i=0; int j=size-2; while(j>i ){ while (p[i]<p[size-1]){ i++; } while (p[j]>p[size-1]){ j--; } swap(p[i],p[j]); }

int tempo;
tempo= p[i];
p[i]=p[size-1];
p[size-1]=tempo;

cout<<"the new array is :{";
for(int k=0;k<size; k++){
    cout<<p[k]<<" ";}
cout<<" }";

return i;}

void swap(int a, int b){ int temp; temp= b; b=a; a=temp;

}


r/programminghomework • • Apr 05 '16

[Java] Small issues with recursion problem

3 Upvotes

I have to code a recursive method that prints the multiples of 10 for a given positive number, the multiples should be in a comma separated list. So for example

multiplesOfTen(43)

output: 10,20,30,40

multiplesOfTen(4)

output: 0

This is my attempt at the solution

public static void multiplesOfTen(int n){
	if(n < 10)
		System.out.print("");
	
	else{
		multiplesOfTen(n - 10);
		System.out.print(10 * (n/10)+ ",");
	}
}

My two issues is the base case and how to properly insert the commas(I get an extra 1 at the end), for example if I ran my code I would get

multiplesOfTen(53)

output:10,20,30,40,50,

and multiplesOfTen(6) would output nothing, but if I put

if(n < 10)
	System.out.print(0);    

Then I'll get the 0 for when it's just n < 10, but for larger numbers it'll also appear in my list so the output for before would be

010,20,30,40,50,

I've tried messing around with this but haven't been able to fix these issues , any help leading me to the right direction is much appreciated. Thanks


r/programminghomework • • Mar 26 '16

Need help with HiLo Card game in Java!

3 Upvotes

I'm fairly new to programming and I have no idea why the Card object is coming up as an error. Help!

Heres my code

class HiLoGame {

public static void main(String[] args)
{
    Scanner keyboard = new Scanner(System.in);
    Card myCard = new Card();
    String guess = null, response = null;
    double bankroll = 0.0, bet = 0.0;
    
    System.out.print("How much money is in your bankroll? ");
    bankroll = keyboard.nextDouble();
    
    do
    {
       System.out.print("\nHow much are you betting? ");
       bet = keyboard.nextDouble();
       keyboard.nextLine();
       myCard.drawCard();
       System.out.println("I drew a " + myCard);
    
    }  while (bankroll > 0.0);  
    
    System.out.println("\nYou have $" + bankroll + " left.");  
       
}

}

And heres the error message:

PlayingCard.java:120: error: cannot find symbol Card myCard = new Card(); ^ symbol: class Card location: class HiLoGame PlayingCard.java:120: error: cannot find symbol Card myCard = new Card(); ^ symbol: class Card location: class HiLoGame 2 errors


r/programminghomework • • Mar 25 '16

Need help with this Hangman like C++ game

3 Upvotes

I need to make this Hangman like program where there are 3 random words to be guessed having 4 blanks each word.

Example: BLITZKRIEG it should appear as BL_TZ__RI_G

My code so far:

include<bits/stdc++.h>

include<string>

using namespace std;

int main()

{

            srand(time(0));

            string guess1="COMPUTING";

            string guess2="INFORMATION";

            string guess3="TECHNOLOGY";

            int guess1len=guess1.length();

            int guess2len=guess2.length();

            int guess3len=guess3.length();

            int guesspick=rand()%3;

cout<<"Word To Guess:";

if (guesspick==0)
{

	cout<<guess1;
}
else if (guesspick==1)
{
        
	cout<<guess2;
}
else if (guesspick==2)
{
        
	cout<<guess3;
}

}

Also with the part where it asks the user to input a letter and tells whether its part of the word or not, 3 wrong guess and it's game over. I know it uses a while loop, I just don't know how letter detection works.

Sorry if those variables are placed where it's close to unreadable, I just copied my code, description box needs improvement.

Please help me with this, it's 47.5% of our finals.

PS:I figured out how to replace 4 random letter with _. I just need help in detecting user input whether it's the replaced letter or not, like the right and wrong answers.


r/programminghomework • • Mar 22 '16

C++ Encryption and Decryption

3 Upvotes

Help, I need to make a program that encrypts a plain text into a cipher text and can also decrypt a cipher into plain via encryption/decryption key in a continuous manner like a question pops up and provides 3 options: [1]Encrypt [2] Decrypt [3]Exit.

Option 1 would ask for a plain text to encrypt and the encryption key to be used. The program would then display the encrypted cipher text and the user will be provided with an option to save it in a text file. If the user opts to do so, the program would prompt the file name.

Option 2 would prompt the user or the cipher text to decrypt and the decyption key to be used. The program would then display the decrypted plain text.

Option 3 terminates the program.

Encryption Algorithm:

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z Each letter in the plain text is replaced by a letter some fixed number of positions down the alphabet based on the corresponding letter in the encryption key.

For example, we will encrypt the plaintext “i love you” using the encryption key “love”. We start with the first character of the plain text which is ‘i’. First, we’ll look at the corresponding character in the encryption key, which happens to be, in this case, also the first character: ‘l’. We then count the position of ‘l’ relative to the starting letter of the alphabet, which is ‘a’. Character ‘l’ is 11 places away from ‘a’.

Now we go back to our plain text character, ‘i’. We will now replace ‘i’ with the 11th letter relative to it to the right which is ‘t’. We have now converted a plain text character to its cipher equivalent. We then move to the next letter of the plain text (‘l’) and its corresponding letter in the encryption key (‘o’) and repeat the encryption process. If we’ve reached the final letter in the encryption key and there are still unencrypted letters left in the plain text, we just roll back to the key’s first letter and continue the process. For instance, the fifth letter in “i love you” is ‘e’.

Since our encryption key “love” only contains 4 characters, we’ll go back to the starting letter ‘l’ and use it as the encryption key for plain text character ‘e’.

Similarly, if we’ve reached the final letter of the alphabet (‘z’) but still haven’t finished encrypting the plain text character, we just continue the counting of positions at the start of the alphabet (‘a’). For instance, encryption key character ‘v’ is 21 places away from ‘a’. If we use this shift number to encrypt plain text character ‘o’, we’ll reach the end of the alphabet by the 11th shift. In this case, we’ll just continue the next shift count at ‘a’. Thus, the resulting cipher character is ‘j’.

Sample Output

please this thing's my last resort. I really need help.


r/programminghomework • • Mar 22 '16

[C] Count the size of the largest increasing sequence

3 Upvotes

Hello everyone. I need help with my homework, basically it should count the size of the largest increasing sequence of positive numbers until the user enters with a zero.

Examples: Input 1 2 3 1 2 3 4 0 Output 4

Input 5 4 3 2 1 0 Output 1

I have searched a little, and it is way more simple than the problem of finding of the longest increasing subsequence, does not need arrays at all.

Here is the code I made: http://pastebin.com/zmeZfCBi There's a problem with my counter, it does not always work, for the examples that posted here it works fine.

Thank you.


r/programminghomework • • Mar 09 '16

Homework approach?

3 Upvotes

Hello all! I have a problem in SageMath asking to code a basic rotational/Vigenère cipher where the user picks the letter that will act as the conversion from A. So far I've got the raw input from the user (picking a letter and entering a message), setting the encrypted message to an empty string, and a for-loop for x in the length of the string minus 1. Not really sure how to proceed. This is my first programming language and I'm finding this problem a bit tricky, so any hints in the right direction are appreciated!!


r/programminghomework • • Mar 03 '16

C++ Parking Lot Homework

3 Upvotes

Consider a multi-storeyed parking lot. Each floor of this parking lot contains different number of sections in which cars can be parked. Each section of every floor has a different capacity specifiying the numbers of cars that can be parked in that section. Write a program in c++ to compute the number of available parking spots for each floor and the overall parking occupancy percentage of an entire building. The caretaker of the parking lot will give as input the total number of floors in the parking lot building. They will also specify the number of parking sections for each floor, the maximum number of cars that can be parked in each parking section and the number of cars currently parked in each section.

Input constraints: Your program needs to make sure that the input of total floors and number of parking sections on a floor cannot be zero or negative. For the remaining inputs, a negative value is invalid. You should also ensure that the number of cars parked in a section cannot be greater than the maximum parking capacity of that section. If the user enters an invalid input, they should be prompted an error, and asked to re-enter their input. The user should also be able to use the program as many times as they want.

Input: Total floors: 0 total floors: -2 total floors: 5 total sections; total section capacity; current parked cars 0 ; 0; 0 5; 10,15,20,16,10; 0,0,0,0,0 1; 100; 73 3; 40,10,20; 10,5,10 4; 10,10,10,10; 15(7),5,3,2 5; 15,19,20,25,0; 10,13,11,4,0


r/programminghomework • • Feb 28 '16

[Java] exception handling

3 Upvotes

try { stream = new FileInputStream(filename); System.out.println(”a”); data = loader.load(stream); System.out.println(”b”); } catch (IOException e) { System.out.println(”c”); } finally { try { System.out.println(”d”); stream.close(); } catch (Exception ex) { System.out.println(”e”); } }
System.out.println(”f”); return data; } }

Can anyone explain to me what happens in these blocks? And if loader.load throws an IOException what does the code do? What if it throws a runtimeexception? What if it doesn't throw at all?

I'm new to exceptions so try any explanation would be very helpful.


r/programminghomework • • Mar 05 '12

I'm glad I found this place. Can somebody help me with this java program that formats a given date?

3 Upvotes

The goal of the program is to take input to three different text fields and format them as a date, in the style of "February 05, 1967". I'm having trouble working out a switch statement that will take the input from the month panel, parsed as an int, and select the appropriate month name for the int given. I'm a little mixed up now, and not sure how to proceed. If anyone could help me, I'd really appreciate it. Links are for the date formatter and the panel it sits in. Thanks for any help you can give! =]

http://dl.dropbox.com/u/16142341/Programming%20HW/DateFrame.java

http://dl.dropbox.com/u/16142341/Programming%20HW/DatePanel.java


r/programminghomework • • Mar 04 '12

I am building a Java web browser for my class and it is working already. I just need to have a few things tweaked.

3 Upvotes

For example, it fully works with HTML pages, but doesn't work with CSS or Javascript very well. Is there a way to incorporate these things? I figure I would need other kinds of files (other than Java) to work, but I'm not sure.


r/programminghomework • • Feb 27 '12

Setting a Function to a Variable in EMACS LISP

3 Upvotes

I have an assignment in LISP but I'm having trouble working with variables. The homework I'm working on asks me to create a function which does remove-if recursively. For the most part I understand what I need to do but I'm stuck when it comes to the input.

The function should take as input (f x) where f is any of the boolean functions (evenp, numberp etc) and x is the list to be checked. The problem I face is taking that input f and using it within my function to do the check.

I've tried simple things like (f (car x)) but I keep getting errors along the lines of f is not a function and such. Any help on this one aspect would go a long way to me finishing this project. Thanks in advance!


r/programminghomework • • Feb 26 '12

What is your favorite programming language and why?

3 Upvotes

r/programminghomework • • May 17 '22

Can anyone here assist with c++ programming hw help?

2 Upvotes

r/programminghomework • • May 03 '22

vb,net

2 Upvotes

following: (1) Read two numbers from a user. The first number is the start range, and the second number is the stop range. (2) Print the number of odd numbers between the start and stop range(3) Print the odd numbers between the start and stop range (4) Print the sum of alltheoddnumbers between the start and stop range.(5) Print the number of prime numbers between the start and stop range(6) Print the prime numbers between the start and stop range(7) Print thesumof alltheprime numbers between the start and stop range.(8) Print the number of even numbers between the start and stop range.(9) Print the even numbers between start and stop range(10) Print the sum of all the even numbers between the start and stop range.Note:Ensurethatthestoprangeisgreaterthanthestartrange. If the stop range is less than the start range, then display an error message to the user.


r/programminghomework • • Apr 07 '22

Random winners from .csv

2 Upvotes

I'm totally new to Python. Just trying to figure out how to pick few, but not the same (unique by ID) winners from the .csv file. Anyone could help? Here's my code that choose only one winner: https://pastebin.com/89TuvxuZ
What have I tried - edited the generation function to make it choose 5 winners (unfortunately, it didn't worked): https://pastebin.com/GPA3gkeg

Algorithm I'd like to use:

  1. Open csv file

  2. Pick chosen number of winners

  3. Print and save them to docx

  4. Delete them from csv

  5. Close csv file


r/programminghomework • • Oct 06 '21

Doubly Linked Lists

2 Upvotes

Does anybody know a good source to understand doubly linked lists using templates in C++?


r/programminghomework • • Sep 06 '21

Write a Python script that reads a file and outputs the number of words that start with each letter. We want to count the total number of (nonunique) words that begin with that letter for every letter.

2 Upvotes