r/programminghelp • • Mar 22 '21

Answered Dealing with two related arrays in Python - Beginner

4 Upvotes

Watson Elementary School contains 30 classrooms numbered 1 through 30. Each classroom can contain any number of students up to 35. Each student takes an achievement test at the end of the school year and receives a score from 0 through 100. Write a Python program that accepts data for each student in the school-classroom number and score on the achievement test. Design a program that lists the total points scored for each of the 30 classrooms.

In other words,  the user should be able to enter a class number and score, and repeat until all the scores are entered, then enter a terminal value like -1.  The class numbers can be in no particular order.  Once the terminal value has been entered, display the total points for each classroom.

How would I initialize the student (score) array? I feel like it would have to be an array inside of the classroom array, but I'm not sure how I would do that? I could also be approaching it wrong. We've only learned the basics - i.e. how to initialize standard arrays, nothing fancy

Edit: After some digging, I found that you can make nested lists.... Would that fix my dilemma?


r/programminghelp • • Mar 20 '21

JavaScript Why would a map return an element 2x more than it should?

4 Upvotes

I have an example where i am trying to map over an array and return individual elements in order to obtain their data to display to the user. The issue is that when I map over my 3 item array, the graph that is supposed to show only 3 elements shows 9 (2 extra for each item). Does anyone know why this would be ? I am using Recharts library.

const dummyCustomerActionsData = [
        {
            key: 1, name: 'Website Visits', uv: 31.47, pv: 2400, fill: '#fcc439',
        },
        {
            key: 2, name: 'Phone Calls', uv: 26.69, pv: 4567, fill: '#848df5',
        },
        {
            key: 3, name: 'Direction Requests', uv: 12.69, pv: 1398, fill: '#79e1c1',
        },
    ];




    const radialChart = dummyCustomerActionsData.map((value) => {
            return (
                <RadialBar key={value.key} onMouseEnter={() => setCenterCustomerText(value.name)} minAngle={15} background clockWise dataKey={"uv"} />
            )
    })



RadialBarChart width={500} height={300} cx={150} cy={150} innerRadius={70} outerRadius={140} barSize={5} data={dummyCustomerActionsData} >
                    {radialChart}
</RadialBarChart>

r/programminghelp • • Mar 11 '21

Other How to open the Fortran compiler in MSyS2 from its terminal?

4 Upvotes

I just downloaded MSYS2 and all the necessary libraries, but i still have no idea how to open the Fortran compiler. Anyone got any idea?


r/programminghelp • • Mar 06 '21

Java Weird problem in android studio found part of the issue.

4 Upvotes

So what seems to be giving the issue is a seekBar. The weird thing is instead of giving me the progess value when I do seekBar.getProgress(); it doens't get the current progress, only what it was when I intalized the seekBar or if I ever set the progress somewhere.

Heres a github with the code, a touch to big to put in a reddit post.


r/programminghelp • • Mar 02 '21

C++ A simple fill() algorithm.

4 Upvotes

Hello. I am a newbie programmer and I need help. This algorithm is supposed to give a number of the 0s next to "a[l][c]". My teacher taught me this and I added the a[l][c]=1 because without that it called the function indefinitly and basically gave no answer. It still does not work. Can somebody help me? (suma means sum)

#include <iostream>

int suma, a[20][20], n, l, c;

using namespace std;

void fill()

{

suma++;

cout << "Suma has increased" << endl;

l--;

if (l > 0 && a[l][c] == 0)

{

a[l][c] = 1;

fill();

cout << "a[" << l << "][" << c<<"] has become 1" << endl;

}

l = l + 2;

if (l < n - 1 && a[l][c] == 0)

{

a[l][c] = 1;

fill();

cout << "a["<<l<<"]["<<c<<"] has become 1"<<endl;

}

l--;

c--;

if (c > 0 && a[l][c] == 0)

{

a[l][c] = 1;

fill();

cout << "a[" << l << "][" << c<<"] has become 1" << endl;

}

c = c + 2;

if (c < n + 1 && a[l][c] == 0)

{

a[l][c] = 1;

fill();

cout << "a[" << l << "][" << c<<"] has become 1" << endl;

}

c--;

}

int main()

{

int i, j;

cin >> n;

for (i = 1; i <= n; i++)

{

for (j = 1; j <= n; j++)

{

cout << "a[" << i << "][" << j << "]= ";

cin >> a[i][j];

}

cout << endl;

}

cin >> l >> c;

suma = 0;

if (a[l][c] == 0)

fill();

cout << suma;

}


r/programminghelp • • Mar 01 '21

C Functions in C

4 Upvotes

Hi, I'm new to programming can anyone explain what's going on in the block that I commented

#include<stdio.h>

int fact(int);

int main(){

printf("enter a number:");

int x;

scanf("%d",&x);

printf("factorial: %d",fact(x));

}

/* i can't understand from here on

int fact(int x)

{

int result=1;

int i;

for(i=1;i<=x;i++){

	result*=i;

}

return result;

}


r/programminghelp • • Feb 27 '21

JavaScript Why am I receiving a UnhandledPromiseRejectionWarning after deploying my create-react-app to GitHub pages?

4 Upvotes

I am coding a react app, and have setup configuration for tailwind css. I recently deployed my app to GitHub pages, and it was working fine. I then added some code and wanted to push to my main, but I was getting a message that I had to make a pull first. I pulled the code from main, there was a new file called robots.txt, and my file system was re-organized a bit, I'm assuming this is because of the deployment to GitHub pages. Anyway, after I pulled I now get this error:

(node:34533) UnhandledPromiseRejectionWarning: TypeError [ERR_INVALID_ARG_VALUE]: The argument 'id' must be a non-empty string. Received '' at Module.require (internal/modules/cjs/loader.js:1084:11) at require (internal/modules/cjs/helpers.js:73:18) at getConfigAsObject (/Users/sam/Desktop/acnh-character-ranking-neo/node_modules/@craco/craco/lib/config.js:46:20) at loadCracoConfigAsync (/Users/sam/Desktop/acnh-character-ranking-neo/node_modules/@craco/craco/lib/config.js:69:34) at Object.<anonymous> (/Users/sam/Desktop/acnh-character-ranking-neo/node_modules/@craco/craco/scripts/start.js:22:1) at Module._compile (internal/modules/cjs/loader.js:1200:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1220:10) at Module.load (internal/modules/cjs/loader.js:1049:32) at Function.Module._load (internal/modules/cjs/loader.js:937:14) at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)

Can anybody help?


r/programminghelp • • Feb 26 '21

C++ Need help editing class variables with a for loop in C++

4 Upvotes

Essentially I am trying to assign values to variables of multiple objects at once.

This is what I thought would work but doesn't seem to work:

Puzzle puzzle1; Puzzle puzzle2; Puzzle puzzle3; Puzzle puzzles[3] = {puzzle1, puzzle2, puzzle3};

for (int i = 0; i < 6; i++) { puzzles[i].width = 3; }

I've been alternating between different projects in c++ and Python, maybe I'm mixing syntax?

Thanks in advance!


r/programminghelp • • Feb 25 '21

Python Python Def function help

4 Upvotes

I'm a relative Python noob, I'm just wondering how I would get the values on the right of the image to increment or decrease depending on weather the number is even instead of the value displayed being -5 or 10. What I hope to be able to do is have the values on the right add up or decrease depending on weather the value produced by the roll is even.

Here is the image: https://imgur.com/ROhw8wU


r/programminghelp • • Feb 19 '21

Answered Program won't give output

4 Upvotes

I'm currently working on a practice assignment and the program isn't giving me any output. I know what the output should be. If I give the following input:

plant Spirea 10

flower Hydrangea 30 false lilac

flower Rose 6 false white

plant Mint 4

-1

The following output is expected:

Plant Information:

Plant name: Spirea

Cost: 10

Plant Information:

Plant name: Hydrengea

Cost: 30

Annual: false

Color of flowers: lilac

Plant Information:

Plant name: Rose

Cost: 6

Annual: false

Color of flowers: white

Plant Information:

Plant name: Mint

Cost: 4

I can't pin down what is wrong with it, so that's why I'm here. Here's my code:

Main.cpp

#include "Flower.h"
#include <vector>
#include <string>
#include <iostream>

using namespace std;

// TODO: Define a PrintVector function that prints an vector of plant (or flower) object pointers

vector<Plant*> myGarden;

void PrintVector() {
   for (int i = 0; i < myGarden.size(); i++) {
       myGarden[i]->PrintInfo();
       cout << endl;
   }

}

int main(int argc, char* argv[]) {
   // TODO: Declare a vector called myGarden that can hold object of type plant pointer
   
   vector <Plant*> myGarden;

   // TODO: Declare variables - plantName, plantCost, flowerName, flowerCost,
   //       colorOfFlowers, isAnnual
   string input;
   string plantName, flowerName, colorOfFlowers;
   int plantCost, flowerCost;
   string isAnnual;

   cin >> input;

   Plant *pl = new Plant();
   Flower *fl = new Flower();

   while(input != "-1") {
   // TODO: Check if input is a plant or flower
   //       Store as a plant object or flower object
   //       Add to the vector myGarden
      cin >> input;
      
     if (input == "plant") {
      
       cin >> plantName;
       cin >> plantCost;
       pl->SetPlantName(plantName);
       pl->SetPlantCost(plantCost);
       myGarden.push_back(pl);

   }
   
   else if (input == "flower") { // type of flower

       //Inputting the flower details

       cin >> flowerName;
       cin >> flowerCost;
       fl->SetPlantName(flowerName);
       fl->SetPlantCost(flowerCost);
       
 cin >> isAnnual;
 bool state;
 if (isAnnual == "false")
 {
  state = false;  
 }
 else if (isAnnual == "true")
 {
    state = true;
 } 
 fl->SetPlantType(state);
 
 cin >> colorOfFlowers;
 fl->SetColorOfFlowers(colorOfFlowers);

 
   }
}

   // TODO: Call the method PrintVector to print myGarden

PrintVector();

   for (size_t i = 0; i < myGarden.size(); ++i) {
      delete myGarden.at(i);
   }
   
   return 0;
}

Plant.h

#define PLANTH

#include <string>
using namespace std;

class Plant {
   public:
      virtual ~Plant();

      void SetPlantName(string userPlantName);

      string GetPlantName() const;

      void SetPlantCost(int userPlantCost);

      int GetPlantCost() const;

      virtual void PrintInfo() const;

   protected:
      string plantName;
      int plantCost;
};

#endif

Plant.cpp

#include "Plant.h"
#include <iostream>

Plant::~Plant() {};

void Plant::SetPlantName(string userPlantName) {
   plantName = userPlantName;
}

string Plant::GetPlantName() const {
   return plantName;
}

void Plant::SetPlantCost(int userPlantCost) {
   plantCost = userPlantCost;
}

int Plant::GetPlantCost() const {
   return plantCost;
}

void Plant::PrintInfo() const {
   cout << "Plant Information:" << endl;
   cout << "   Plant name: " << plantName << endl;
   cout << "   Cost: " << plantCost << endl;
}

Flower.h

#ifndef FLOWERH
#define FLOWERH

#include "Plant.h"
#include <string>
using namespace std;

class Flower : public Plant {
   public:
      void SetPlantType(bool userIsAnnual);

      bool GetPlantType() const;

      void SetColorOfFlowers(string userColorOfFlowers);

      string GetColorOfFlowers() const;

      void PrintInfo() const;

   private:
      bool isAnnual;
      string colorOfFlowers;
};

#endif

Flower.cpp

#include "Flower.h"
#include <iostream>

void Flower::SetPlantType(bool userIsAnnual) {
   isAnnual = userIsAnnual;
}

bool Flower::GetPlantType() const {
   return isAnnual;
}

void Flower::SetColorOfFlowers(string userColorOfFlowers) {
   colorOfFlowers = userColorOfFlowers;
}

string Flower::GetColorOfFlowers() const {
   return colorOfFlowers;
}

void Flower::PrintInfo() const {
   cout << "Plant Information:" << endl;
   cout << "   Plant name: " << plantName << endl;
   cout << "   Cost: " << plantCost << endl;
   cout << "   Annual: " << boolalpha << isAnnual << endl;
   cout << "   Color of flowers: " << colorOfFlowers << endl;
}

Thanks in advance!


r/programminghelp • • Feb 10 '21

Java Issues with Thread.sleep() and delayed text

4 Upvotes

SEE EDIT.

Hi, I am having trouble printing text one character at a time with a delay in between each one (Text base game). It works perfectly if I use 250 or higher for thread.sleep(), but when I try to use 100 or 200 it takes a few seconds of printing nothing, then outputs the entire text at once. My code:

char[] cArray = aString.toCharArray();

System.out.print("\n");

for (int i = 0; i < cArray.length; i++)

{

System.out.print(cArray[i]);

try {

Thread.sleep(100);

} catch (InterruptedException e){

Thread.currentThread().interrupt();

break;

}

}

Any help is greatly appreciated :).

Edit: So the problem seems to be thread.sleep isn't great in a loop. Any other suggestions for making text print slowly with one character at a time?


r/programminghelp • • Jan 26 '21

C# Update item or create new if not exist c#

4 Upvotes

r/programminghelp • • Jan 24 '21

JavaScript What is curl and can you get it on windows?

4 Upvotes

Okay, so I have an API, along with a key for it. They require me to authenticate my key and I have no clue how to do that. Here are the instructions, I'm hoping I could get some help here.

curl --request GET \

--url 'https://api.climacell.co/v3/locations' \

--header 'content-type: application/json'

--header 'apikey: API_KEY'

The API I plan to use is ClimaCell and it can be found here.

Any/All help will be greatly appreciated


r/programminghelp • • Jan 15 '21

Java JAVA- KINETIC ENERGY

4 Upvotes

Hello experts and fellow learns, I'm stuck with this problem for a while and utilize all resources that I have for this activity but I can't seem to get it right. This is also a self study as Im not able to understand the lesson from our class due to poor internet connection, I need to call a function to get the object's kinetic energy. I appreciate your suggestions, tips, and helps etc. Thanks in advance.

This is my code:

import java.util.Scanner;

public class MyClass {

public static void main(String args[]) {

Scanner input = new Scanner(System.in);

double KE, m, v, ObjectKE;

System.out.print("Enter mass in kilograms:");

m = input.nextDouble();

System.out.print("Enter velocity in meters per second:");

v = input.nextDouble();

System.out.print("The object's kinetic energy is:");

KE= input.nextDouble();

System.out.print("The object's kinetic energy is: " + ObjectKE + "J");

}

public static double KineticEnergy (double m , double v){

double ObjectKE = (m * (0.5) * (Math.pow(v,2)));

return ObjectKE;

}

}

Result:/MyClass.java:12: error: variable ObjectKE might not have been initialized

System.out.print("The object's kinetic energy is: " + ObjectKE + "J");

^

1 error


r/programminghelp • • Jan 11 '21

Java I dont understand how this for loop works as d and n are not defined as variables so how does this code work? This code prints the times tables of 5.

4 Upvotes

public class MultiplicationTable {

public static void main(String[] args) {

int num = 5;

for(int i = 1; i <= 10; ++i)

{

System.out.printf("%d * %d = %d \n", num, i, num * i);

}

}

}


r/programminghelp • • Jan 01 '21

HTML/CSS Code language not supported or defined?

4 Upvotes

Recently started diving into html to eventually build a website. Downloaded VS Code and selected HTML as the language but can’t seem to get the editor to read it when I hit “run”. This is all I’ve put into the editor to test it out. Not sure if something is wrong with how I’m writing it or if it may be a software error. Any suggestions?

1 <!DOCTYPE html> 2 <head> 3 <title>Welcome to VS CODE Practice</title> 4 </head> 5 <body></body> 6 </html>


r/programminghelp • • Dec 24 '20

Python What sorting algorithm is this?

4 Upvotes

I was trying to implement bubble sort and I wrote this, it isn't bubble sort since I'm not comparing adjacent elements but it's like a combination of bubble sort and selection sort and still works to sort lists, so I'm wondering what this algorithm is called or if it even has a name?

(I'm aware it's inefficient because best and worst case are both O(n ^ 2))

#!/usr/bin/env python3

def sort(x):
    n = len(x)
    for i in range(n):
        for j in range(i+1, n):
            if (x[j] < x[i]):
                temp = x[j]
                x[j] = x[i] 
                x[i] = temp
    return x

r/programminghelp • • Dec 19 '20

C++ My while loop won't end (C++)

4 Upvotes

Hey guys, I don't understand why my while loop doesn't end in the code below. It is supposed to stop when n<=2 but when it's value is 1 it keeps going infinitely. If someone knows what I'm doing wrong I'd love the help!

Here's the code:

#include <iostream>

using namespace std;

int main()

{

int l=1;

int lmax=0;

int nmax=0;

int ni;

for (int n=456;n<1110;n++){

ni=n;

while(n>=2){

if (n%2==0){

n=n/2;

cout <<n<< " pair"<<endl;

}else{

n=3*n+1;

cout <<n<<" impair"<< endl;

}

l=l+1;

cout<<l<<" iterations"<<endl;

if (n==1){

break;

}

}

if (l>lmax){

lmax=l;

nmax=ni;

}

}

cout <<"La sequence maximale dure " <<lmax<<" itterations et a un nombre initial de "<<nmax<<endl;

return 0;

}


r/programminghelp • • Dec 13 '20

JavaScript I'd like to write a class to handle interaction between my server and an API. Is this typical?

4 Upvotes

Hello all,

I have been given an extremely rare opportunity to write code for my tech company despite being in a non-software position, and I'd like to impress.

I have a background in Python and a bit of C++, but for this project I'm using Node.js. In an effort to make my code as clean as possible, I'm trying to create a class that handles and abstracts all my API interactions.

However, every single tutorial I read/watch and every example source code has a much more freeform structure.

What is the typical, recommended approach here? Any good source code examples?

Any help at all is much appreciated, thank you.


r/programminghelp • • Dec 07 '20

C My implementation of EqualsIgnoreCase in C is not working

4 Upvotes

I am currently attempting to program a sort of database in C.

When I create a new character for the database, it should not have the same name as any other character, case-insensitive - so, if "Amy Bob Carol" exists, I should not be able to add a new user "aMy boB cArOl".

So, this is my approach, but it doesn't seem to work:

DBPerson* create_character(char* name)
 {
    DBPerson* person = (DBPerson*)malloc(sizeof(DBPerson);
    if (alreadyInDB(name))
     {
      free(person);
      return null;
     }
    strcpy(person->name, name);
    person->friendship = 0;
    person->spouse=NULL;
    addToAllPeople(person); //this adds them to the master list of all people
 return person;
 } 

The helper functions alreadyInDB and isSame are as follows:

int isSame(char* a, char* b)
 {
  for (int i = 0; i < MAX_STR_LEN && a[i]!='\0' && b[i]!='\0'; i++)
  {
   if (tolower(a[i]) != tolower(b[i]))
   {
      return 0;
   }
  }
  return 1;
  }

  int alreadyInDB(char* name)
  {
   DBPerson* tmp = allPeople;
   while(tmp!=NULL)
    {
    if(isSame(name, tmp->person->name))
    return 1;
    tmp=tmp->next;
    }  
   return 0;
   } 

I am importing all necessary libraries - ctype.h, string.h, stdlib.h, stdio.h Yet if I run it and try

 DBPerson* niko1 =create_character("NiKolAj");
 DBPerson* niko2 =create_character("nikolaj"); 

both characters are successfully made.

I have spent hours looking over this but cannot find any answer. Does anyone have any insight?


r/programminghelp • • Dec 05 '20

PHP What do I need to learn to pull this off?

4 Upvotes

Say I'd like to create a website that allows people to login with their e-school accounts and basically see the same things that they can see on the official site but redesign in a different way.

What web development skills do I need for that?

Basically, I just want to redesign a webpage that already exists and has the same functionality and uses the data that is already on the original site, but just looks different.

Can I use Java for this?


r/programminghelp • • Dec 04 '20

Python How to Pass by Reference (equivalently) in Python using threading?

4 Upvotes

I know python doesn't support pass by reference, but I'm stumped on how to get around this. I'm using a thread to run a function that accepts a queue as a parameter, and I want the queue to be updated in the main function as the thread runs. Any ideas? Here's the general idea:

class foo():  
    def readInput(self, queue):
        if(input):
        queue.put(self)

def bar:
    queue = Queue()
    thread = threading.Thread(target=foo.readInput, args=(queue, x))
    thread.start()
    while True:
        if(queue.qsize() == 2):
            print(2)
            return

r/programminghelp • • Dec 01 '20

C How to link math.h using makefile for gcc

4 Upvotes
CC = gcc
CFLAGS = -O

default: run

run: build
	run < program.cs 
build: compile
	$(CC) -o run main.o closed_hashtable.o 
compile: main.c closed_hashtable.c closed_hashtable.h 
	$(CC) -c main.c 
	$(CC) -c closed_hashtable.c 
clean:
	$(RM) *.o *.gch

How do I link math.h using the makefile above?


r/programminghelp • • Nov 29 '20

C Need some help with my C program.

4 Upvotes

Hi, i need some help in my C program. My task is to create a program that will create a N*N matrix and read its biggest and smallest elements in every row along with their location and then print out the matrix along with the smallest and biggest element in every row.

So far i've got most of it working except for those issues:

  • location/coordinates of printed results are wrong

  • maximum elements are read correctly but the minimum results are wrong. it always prints out first element of every row along with its wrong coordinates

  • the requirement of the task states that i have to use at least 1 more function different from main. I do not understand how to do this, essentially i need to split the program into at least 2 functions.

If someone could please take a look at my code and fix it up a bit i would be really thankful.

#include<stdio.h>

int main(){
    int m;                                                          //user interface
    printf("Input a number defining the row/column size of the matrix (N*N): ");
    scanf("%d",&m);
    printf("Please input " "[%d]*[%d]" " matrix elements.\n\n",m,m);

    int matrix[m][m], col, row;
    for(col=0;col<m;col++){                                        // filing the matrix
        for(row=0;row<m;row++){
            printf("Define [%d][%d] element: ",col,row);
            scanf("%d", &matrix[col][row]);}
            printf("\n");
                    }
                                                                    // printing out the matrix
    printf("Entered matrix:\n");

    for(col=0;col<m;col++){
        for(row=0;row<m;row++){
            printf("%d\t",matrix[col][row]);}
        printf("\n");
                    }
printf("\nLargest elements in every row of the matrix:");
    for(col = 0;col < m;col++){
        int max = matrix[col][0];
    for(row = 0;row < m;row++){                                     // determining the largest row element along with its coordinates
        if(max < matrix[col][row]) max = matrix[col][row];
                        }
        printf("\nElement [%d], is the largest in row [%d] at column[%d]",max,col,row);
                        }

printf("\n\nSmallest elements in every row of the matrix:");
    for(col = 0;col < m;col++){
        int min = matrix[col][0];
    for(row = 0;row > m;row++){                                     // determining the smallest row element along with its coordinates
        if(min < matrix[col][row]) min = matrix[col][row];
                        }
        printf("\nElement [%d], is the smallest in row [%d] at column[%d]",min,col,row);
                        }
return 0;}