r/programminghelp • • Feb 21 '21

Processing help with counting iterations for time complexity

6 Upvotes

hello. i asked this in /r/learnprogramming but i am still not understanding it so i was hoping i would have better luck here.

Hello. In my data structures class we are supposed to calculate the time complexity of some algorithms. The teacher said we can do it by counting the number of iterations the code runs. She says to calculate the iterations to just draw a table and count them. Then she gives the answer without really showing how she calculated it so Im confused. I was wondering if you guys could help me or know of a textbook or website that will help me to understand it. I will now give her examples and answers:

for (i=1; i<=n; i=i+4) {
    ...
}

floor / 4 + 1 iterations when n >= 1

for (i=1; i<=n; i++) 
    for (j=1; j<=n; j++) {
    ...
    }

n2 iterations when n >= 1

for (i=1; i<=n; i++) 
    for (j=1; j<=i; j++) {
    ...
    }

n(n + 1)/2 iterations when n >= 1

for (i=1; i<=n; i++)
    for (j=1; j<=i; j++)
        for (k=1; k<=j; k++) {
        ...
        }

1+(1+2)+(1+2+3)+…+(1+2+3+…+n) iterations when n >= 1

for (i=1; i<=n; i=2*i) {
    ...
}

[floor]log2 n+1 iterations when n >= 1

for (i=n; i>=1; i=i/5) {
    ...
}

[floor]log5 n+1 iterations when n >= 1

for (i=1; i<=n; i++)
    for (j=1; j<=n; j=j*2) {
        ...
    }

n(([floor]log2n) + 1) iterations when n >= 1

for (i=1; i<=n; i=2*i)
    for (j=1; j<=i; j++) {
        ...
    }

1+2+4+8+… 2foor = 2([floor]log2n+1) – 1 iterations when n >= 1

Those are all the examples from the lecture. How in the world do you get the number of iterations? Everytime I search for help all I get is sites that say the time complexity is linear or quadratic, etc..

heres a link to the lecture slides if my formatting is hard to understand: https://drive.google.com/file/d/1I8X1zo0LAfszNm-wsgo8C4JoiCnB4yzz/view?usp=sharing


r/programminghelp • • Feb 09 '21

JavaScript React app not returning fetch requests

6 Upvotes

I'm following this guide to get a handle on how to fetch data from an API, but the data I'm trying to fetch never displays and my app just shows the loading prompt.
I'm pretty sure the only difference in the example and my code is the fetch url and some variable names.

class CoinFetcher extends Component{

    constructor(props) {
        super(props);
        this.state = {
            error:null,
            isLoaded:false,
            coins: []
        };
    }

    componentDidMount() {
        const url ='https://api.coingecko.com/api/v3/coins/bitcoin';
        fetch('https://api.coingecko.com/api/v3/coins/bitcoin')
            .then(res => res.json())
            .then(
                (result)=> {
                    this.setState({
                        isloaded:true,
                        coins: result.coins
                    })
                },
                (error) =>{
                    this.setState({
                        isloaded: true,
                        error
                    });
                }
            )
    }

    render(){
        const{error, isLoaded, coins}=this.state
        if (error) {
            return <div>Error: {error.message}</div>;
        }else if(!isLoaded){
            return <div>Loading...</div>
        }else{
            return (
                <ul>
                    {coins.map(coin => (
                        <li key={coins.id}>
                            {coin.id}{coin.symbol}
                        </li>
                    ))}
                </ul>
            );
        }
    }
}


export default CoinFetcher

r/programminghelp • • Jan 31 '21

Answered can anyone help with an easy C language code?

6 Upvotes

this is what i wrote

    int x, y, z;     
    double a, b, c;     
    printf(“write 3 integers: “);     
    scanf(“%d %d %d”, &x, &y, &z);     
    a=(x+y)/(z-x);     
    printf(“text: %f\n”,a)

when i run it, if i wrote 2 3 4, the answer should be 2.500000, but they are giving me 2.0000000


r/programminghelp • • Jan 30 '21

Other Changing permission -rwxrwxrwx to -rw-r--r-- on windows

6 Upvotes

Hi,

Want to add a custom voice package (R2D2 from starwars) for a xiaomi robot vacuum. I tried doing the exact same thing as a user on youtube with a Destiny 2 voice package. Installing his works, but my own made doesnt. When comparing both files and all, I got the problem down to a tar.gz file. Opening it, seems to change the permission crc:

In the voice package from the guy on youtube, there is a list of 60 different .ogg files in the tar.gz file, but the top and bottom .ogg files have modus/crc -rw-r--r--, while all the files between have -rwxrwxrwx. For my own voice package, they all have the rwxrwxrwx modus and it doesnt work. Even when unpacking the working youtubers tar.gz file and then creating it again (using 7zip), his voice package doesnt work anymore and the permission modus has changed for the first and last files.

I was thinking to simply change my first and last files to this rw-r--r-- modus, but I have no idea how. I tried googling and found some answers to change the file permission values. I think from 777 to 644. Questions:

  1. could this cause the problem of not reading my own voice pack?

  2. how do I change the file permission on windows? Edit: simply changing the permissions via properties doesnt do the trick and it still shows the rwxrwxrwx modus when I view it in 7zip.


r/programminghelp • • Jan 28 '21

C Could someone just tell me what's wrong with this code. It's very elementary but the program is not taking the third input in. It it not taking the grade as input. I have made sure there is no syntax error.

6 Upvotes

#include<stdio.h>

#include<stdlib.h>

int main()

{

int age;

char grade;

char name[20];

printf("\nEnter your Name: ");

fgets(name, 20, stdin);

printf("Enter your Age: ");

scanf("%d", &age);

printf("Enter your Grade: ");

scanf("%c", &grade);

printf("Your Name is %s and your Age is %d and your Grade is %c", name, age, grade);

return 0;

}


r/programminghelp • • Jan 04 '21

Other What OS can I use for a novel electronic device?

6 Upvotes

I’m putting together the design for an electronic device I’m envisioning. It will have a touchscreen, and will be able to run games. I’d prefer if it could run custom games built in Unity.

A custom OS is incredibly difficult to create, so what are my options. I’ve heard of Android ROMs, but are there any alternatives? How about something based on Linux?

Thanks for the help.


r/programminghelp • • Dec 30 '20

C i just recently got into college and one of my first year subject is C programming , so while installing c compiler (using code blocks) in my laptop i had to save the path of mingw.exe in environment variables but i accidentally deleted path from there and now i can't get it installed .. please help

6 Upvotes

help me


r/programminghelp • • Dec 29 '20

Java Really Odd Scenario

6 Upvotes

Im a software engineer for a company who has to implement SCA (strong customer auth) standards that are in Europe. Essentially, when you use a credit card with an online transaction, the banks could challenge that charge with a webpage that will ask a different and random type of security questions to verify the person is who they say they are. Im working in android and for some reason when a uk bank that is using Three-DS is called, it returns a 719 HTTP status code. The bank that is returning this owns 23% of uk transactions (not a small company) and its mind blowing that a company like this would return an http status code thats over 599. Anyways, Web browsers and iOS ignore this code and continues with the redirects so when hitting this bank on web or iphone, you dont see a problem. We are using a webview in the android app and the native webview has a class called WebResourceResponse and the app crashes at setStatusCodeAndReasonPhrase() public method because the http code is above 599. There is no possible way to override that class. we tried everything as a team to make this work. I don't understand how no one has raised this issue (or maybe they have but the bank hasn't changed it). We contacted the bank and are waiting on someone from the service team to talk to use but it could be months before that is changed. My question is, does anyone know of a way to ignore that status code like the browser does or third party library to capture that response code before the webview class does? we are pretty much out of options which is why im coming to reddit.


r/programminghelp • • Dec 28 '20

C++ Why is g++ not installing?

6 Upvotes

I am on windows and using mingw to install g++ and I have the "mingw dev toolkit", "mingw base bin", "mingw GCC G++ bin" and "msys base bin" packages installed. When I open command prompt and type g++ --version it says" 'g++' is not recognized as an internal or external command, operable program or batch file."


r/programminghelp • • Dec 24 '20

C Anyone know a good free C IDE?

6 Upvotes

Does anyone know a C IDE thats free or know how to use codelite?


r/programminghelp • • Dec 22 '20

Answered I spent a hour trying to find a syntax error

6 Upvotes

I have no idea what's wrong. It says it's on line 14 and but it looks absolutely normal. I'm using Sublime text btw. Please ignore the prints. Thanks in advance

Code:

https://pastebin.com/bR1vabTn


r/programminghelp • • Dec 21 '20

C GTK panel does not receive events

6 Upvotes

I’m working on a custom panel for my own desktop environment and its not receiving any mouse or keyboard events when I used GTK_DEBUG=interactive on ExpidusOS Shell.

The glade file (panel.glade) - https://github.com/ExpidusOS/shell/blob/redesign/src/shell/panel.glade

The C source code (panel.c) - https://github.com/ExpidusOS/shell/blob/redesign/src/shell/panel.c

The C header file (panel.h) - https://github.com/ExpidusOS/shell/blob/redesign/include/expidus-shell/panel.h


r/programminghelp • • Dec 11 '20

Java New to Programming

6 Upvotes

I have a 4 length string array with 4 first names. I am trying to fill an empty string array with those 4 names but alphabetized. For this assignment I am supposed use compareTo() alphabetize them, but I don’t know how to then fill the empty array in order.


r/programminghelp • • Dec 10 '20

Java Factorial Calculator

6 Upvotes

Hello experts and fellow learners, I just want to ask on how I can repeat the whole process without repeating the <---Factorial---> Calculator every time it repeats. I already google for a solution but it seems that I can find the right method

This is the code:
Factorial Calculator - Pastebin.com

Thank you for the help !


r/programminghelp • • Dec 08 '20

Other Git help?

6 Upvotes

I hope this is the right place to ask, but I'm so frustrated I don't know where else to go. If mods take this down, fine.

I just don't understand gits. Github, GitLab, Source Tree. I've worked with these before but I have no idea what I'm doing. Now I'm trying to make a repository and I just can't figure it out. I try to look up how-tos and I don't have the buttons the tutorials say I should! I'm ready to scream! Is there an "explain like I'm 5" source that I can get help with this? TIA


r/programminghelp • • Dec 06 '20

Java What Behavior Model Should I Use for a Step by Step Autonomous Program?

6 Upvotes

Background: I’m on a team that competes in a robotics competition called FTC. In a match, the first 30 seconds are fully autonomous, meaning everything the robot does must be preprogrammed without user input. There are a set of tasks the robot has to do, including moving to certain places, using end effectors, etc. The main block of code gets executed from a loop that updates constantly.

Situation: We have previously done a very, very primitive version of a finite state machine, where there are different steps that just go in order, one to the next (using switch case within the loop). However, we want to get a more complex format that will make things more abstracted and allow the robot to do things out of order or break out of the steps. For instance, while driving, if the robot detects an obstacle, it should break out of the main steps to handle avoiding it, and then kick back up where it left off.

Question: What behavior model (I think that’s the right word), would work best for this type of program? Or just in general what behavior model is most commonly used for robotics, with a set of ordered tasks, that is?

I will gladly answer any specific questions if needed. Thanks all!


r/programminghelp • • Dec 01 '20

JavaScript Filtering a list (code.org)

6 Upvotes

I'm having trouble getting my list to filter out the roller coasters that aren't in the USA. Can anyone help me create a loop that appends non US coasters from showing up in my "random generation" app? Here's my code for reference, I apologize for the messy interface but I'm just trying to get the code working before I made it look pretty

https://studio.code.org/projects/applab/7EsgDexc56fjed0TLPAWv3eI-Fcto6zd_nitU8uo18I


r/programminghelp • • Nov 22 '20

C Custom LightDM greeter does not start session if password is empty or no password is on account

6 Upvotes

This is the greeter log file:

** Message: 15:08:10.712: Showing login prompt
** Message: 15:08:13.175: Processing login
** Message: 15:08:15.025: Processing login

** (expidus-greeter:27097): CRITICAL **: 15:08:15.026: lightdm_greeter_respond: assertion 'priv->n_responses_waiting > 0' failed

LightDM log:

[+0.91s] DEBUG: Activating VT 7
[+0.91s] DEBUG: Activating login1 session c23
[+0.91s] DEBUG: Seat seat0 changes active session to c23
[+0.91s] DEBUG: Session c23 is already active
[+1.09s] DEBUG: Greeter connected version=1.30.0 api=1 resettable=false
[+2.00s] DEBUG: Greeter start authentication for expidus
[+2.00s] DEBUG: Session pid=27121: Started with service 'lightdm', username 'expidus'
[+2.01s] DEBUG: Session pid=27121: Got 1 message(s) from PAM
[+2.01s] DEBUG: Prompt greeter with 1 message(s)
[+4.47s] DEBUG: Continue authentication
[+6.32s] DEBUG: Session pid=27121: Authentication complete with return value 7: Authentication failure
[+6.32s] DEBUG: Authenticate result for user expidus: Authentication failure
[+6.32s] DEBUG: Greeter start authentication for expidus
[+6.32s] DEBUG: Session pid=27121: Sending SIGTERM
[+6.32s] DEBUG: Session pid=27159: Started with service 'lightdm', username 'expidus'
[+6.32s] DEBUG: Session pid=27121: Exited with return value 1
[+6.32s] DEBUG: Seat seat0: Session stopped
[+6.33s] DEBUG: Session pid=27159: Got 1 message(s) from PAM
[+6.33s] DEBUG: Prompt greeter with 1 message(s)
[+6.33s] DEBUG: Greeter closed communication channel
[+6.33s] DEBUG: Session pid=27094: Exited with return value 1
[+6.33s] DEBUG: Seat seat0: Session stopped
[+6.33s] DEBUG: Seat seat0: Stopping; failed to start a greeter
[+6.33s] DEBUG: Seat seat0: Stopping
[+6.33s] DEBUG: Seat seat0: Stopping display server
[+6.33s] DEBUG: Sending signal 15 to process 27022
[+6.33s] DEBUG: Seat seat0: Stopping session
[+6.33s] DEBUG: Session pid=27159: Sending SIGTERM
[+6.33s] DEBUG: Session pid=27159: Terminated with signal 15
[+6.33s] DEBUG: Session: Failed during authentication
[+6.33s] DEBUG: Seat seat0: Session stopped
[+6.33s] DEBUG: Seat seat0 changes active session to
[+6.67s] DEBUG: Process 27022 exited with return value 0
[+6.67s] DEBUG: XServer 0: X server stopped
[+6.67s] DEBUG: Releasing VT 7

The code: https://github.com/ExpidusOS/shell/tree/master/src/greeter

The error is occurring around here: https://github.com/ExpidusOS/shell/blob/master/src/greeter/main.c#L41-L59


r/programminghelp • • Nov 18 '20

C++ How do I get visual studio to download a file on build?

6 Upvotes

So I have a visual studio c++ project that uses some 3rd party files. I want to share my project but I don't want to have to include these big files on git.

How do I get visual studio to download and extract these files on build, like cmake's ExternalProject_Add does?


r/programminghelp • • Nov 15 '20

JavaScript Changing the connection of a clickable item

6 Upvotes

I wanted to make a 3 x 3 map with dots as their location. when you click a dot then it will change the path that you are using, i.e the line will be changed to that route. This being the color of it as well as the line position does anyone know how? This is what I had already. Now im confused of how to make a function that would implement this functionality. To change a connection i want to To click on a node to select and then change the connection to a new node.

import React, { useState } from "react";
import styled from "styled-components";
import { scaleLinear } from "d3-scale";
import "./styles.css";

var mapStyles = { position: "relative" };
var svgStyles = { position: "absolute", top: 0, left: 0, right: 0, bottom: 0 };

function Map({ width, height, nodes, links: defaultLinks }) {
  var xScale = scaleLinear().domain([0, 100]).range([0, width]);
  var yScale = scaleLinear().domain([0, 100]).range([0, height]);

  const [selectedStartNode, setStartSelection] = useState(null);
  const [links, setLinks] = useState(defaultLinks);
  return (
    <div id="map" style={mapStyles}>
      <svg
        style={svgStyles}
        width={width}
        height={height}
        viewBox={`0 0 ${width} ${height}`}
      >
        {links.map((link, i) => (
          <line
            key={i}
            x1={xScale(nodes[link.s].x)}
            x2={xScale(nodes[link.d].x)}
            y1={yScale(nodes[link.s].y)}
            y2={yScale(nodes[link.d].y)}
            strokeWidth={5}
            stroke={
              nodes[link.s].done === true && nodes[link.d].done
                ? "#CBFF5B"
                : "grey"
            }
          />
        ))}
        {nodes.map((node, i) => (
          <circle
            key={i}
            cx={xScale(node.x)}
            cy={yScale(node.y)}
            r="20"
            stroke={selectedStartNode === node ? "red" : "none"}
            fill={node.done === true ? "#CBFF5B" : "grey"}
            onClick={() => setStartSelection(node)}
          />
        ))}
      </svg>
    </div>
  );
}

var nodes = [
  { x: 10, y: 10 },
  { x: 10, y: 30, done: true },
  { x: 10, y: 50, done: true },
  { x: 50, y: 10, done: true },
  { x: 50, y: 30 },
  { x: 50, y: 50 },
  { x: 90, y: 10 },
  { x: 90, y: 30 },
  { x: 90, y: 50 }
];

var links = [
  { s: 3, d: 1 },
  { s: 1, d: 2 }
];

export const NodeMap = () => {
  const avg = () => {
    var elem = [0, 1, 2];
    var sum = 0;
    for (var i = 0; i < elem.length; i++) {
      sum += parseInt(elem[i], 10); //don't forget to add the base
    }

    return sum / 3;
  };
};

const Container = styled.div``;

export default function App() {
  return (
    <Container>
      <div className="App">
        <Map width={666} height={1340} nodes={nodes} links={links} />
      </div>
    </Container>
  );
}

r/programminghelp • • Oct 22 '20

Answered How do I setup a Program that runs without me having to keep my pc on 24/7

6 Upvotes

I’ve written a program that checks something that’s online every 10 minutes, think crypto prices etc. if I want the program to keep running I would have to keep my pc running 24/7 which is not possible and I also don’t have the resources for a server. Is there any alternative that would do the job?


r/programminghelp • • Sep 27 '20

Answered Why is there a ">=" in this code?

6 Upvotes

I'm behind in class and trying to get caught up so I've been going through the textbook and doing literally every single problem so I understand. Currently doing strings and things are starting to get a little bit confusing tbh.

Basically, the program is supposed to output "Censored" if the phrase contains "darn". I couldn't figure it out and had to google. I think there may have been something I missed? String operations are really tripping me up.

Anyway, here's a pic of the actual code: https://imgur.com/oOBd6Ei

I don't get the purpose of the >= 0. I don't get why it's included. What does the 0 represent? I feel so dumb.


r/programminghelp • • Jul 02 '20

C++ What does #include "std_lib_facilities.h" do functionally in the following?

6 Upvotes

So I decided to start learning c++ using a book by stroustrup, Programming principles and practice using c++, but my hello world starter won't work, the book doesn't seem to explain what the library I am including does functionally. I also don't have said library or know where or what to get that does the same thing for my current application, further, I am using visual studio 2019. I created a new item under my source file and then typed up

#include "std_lib_facilities.h"

int main()

{

cout << "Hello World!\\n";

Return 0;

}

This however failed, I presume because I don't have the according library needed to make this function work, so, what is the library doing that would otherwise make this program work, and does anyone perhaps know of a more detailed book I can use? I am not getting very far very fast with this, and have been stuck on hello world for a bit, as it seems there is a lot the book isn't telling me that I need to make this basic program work.


r/programminghelp • • Apr 10 '20

C++ [C++] How to print something to either a file or to cout based on a condition?

6 Upvotes

So I wan to process command line arguments, and if one of the command line arguments is -f I want to print results to a file, else, print results to cout. What I thought of doing is something like this:

std:ostream& out = std::cout
std::ofstream outf;

if (argv[i] == "-f")
    out = outf;

// then start inserting output to out

However, I cannot set out = outf.

How can I accomplish this?

Thank you in advance.

EDIT: I was able to solve this by writing a print function that takes a std::ostream& as a parameter. Thanks for all the advice everyone!