최근에 다시 자바스크립트로 돌리면서, 기존에 파이썬으로 했던 것들 다시 모두 자바스크립트로 풀어보면서 문제 풀어보니, 발견했습니다. 이거 첫번째 가정을, 그리디로 접근하면 해결 안되는 문제인것같습니다. 이후 가정들은 당연히 그리디 관념으로 최적값 찾을 수 있는데, 첫번째 가정부터 그리디로 접근하면 해결되는 문제가 아니라서 어긋나기때문에, 그리디관념이 통하지 않는 문제인것같습니다. 완전탐색해버리거나, 시간 더 줄이려면 백트래킹 가지치기 해야하는 문제인것같습니다. 입력입니다! 7 172 67 183 65 179 61 178 62 177 63 170 72 181 60 기존 풀이(무조건 183선발) 가 내주는 답 : 3 감독 현수가 원할 것 같은 답 : 6 그리디로 가장 키 큰 사람 무조건 선발하는 과정이 풀이에서 오류인것같습니다. 183 선발 가정하고 cnt 값 구하고, 그다음 181 선발 가정하고 cnt값 구하고, 쭉 다음 순으로 선발 가정하고 cnt값 구하는데, 만약 어떤 사람 선발 가정하고 cnt값 구하는데 남은 사람 수 다 합해도 기존 Max cnt보다 적을 경우, 백트레킹 가지치기로 break 혹은 return 끊어버리는게 맞는것같습니다. 풀이1. 이중포문 const input = require("fs") .readFileSync("input.txt") .toString() .trim() .split("\n"); const n = parseInt(input[0]); const arr = Array.from(Array(5), () => []); for (let i = 0; i < n; i++) { arr[i] = Array.from(input[i + 1].trim().split(" ")).map((v) => parseInt(v)); } function solution(n, arr) { arr.sort((a, b) => b[0] - a[0]); let cnt = 0; let largest = 0; let res = 0; for (let i = 0; i < n; i++) { largest = arr[i][1]; cnt += 1; if (res >= n - i) { break; } for (let j = i + 1; j < n; j++) { if (arr[j][1] > largest) { largest = arr[j][1]; cnt += 1; } } res = Math.max(res, cnt); cnt = 0; } console.log(res); } solution(n, arr); 풀이2. DFS const input = require("fs") .readFileSync("input.txt") .toString() .trim() .split("\n"); const n = parseInt(input[0]); const arr = Array.from(Array(5), () => []); for (let i = 0; i < n; i++) { arr[i] = Array.from(input[i + 1].trim().split(" ")).map((v) => parseInt(v)); } let cnt = 0; let res = 0; //const list = []; function DFS(s, weight) { if (s < 0) return; if (cnt + n - s <= res) { cnt -= 1; s -= 1; return; } for (let i = s; i < n; i++) { if (arr[i][1] > weight) { cnt += 1; //list.push(arr[i][1]); DFS(i + 1, arr[i][1]); //list.pop(); } } res = Math.max(res, cnt); //console.log(list); cnt -= 1; } function solution(n, arr) { arr.sort((a, b) => b[0] - a[0]); DFS(0, 0); console.log(res); } solution(n, arr);
따라하며 배우는 노드, 리액트 시리즈 - 레딧 사이트 만들기(NextJS)(Pages Router)
_app.tsx export default function App({ Component, pageProps }: AppProps) { axios.defaults.baseURL = process.env.NEXT_PUBLIC_SERVER_BASE_URL + '/api'; axios.defaults.withCredentials = true; const { pathname } = useRouter(); const authRoutes = ['/register', '/login']; const authRoute = authRoutes.includes(pathname); return ( <AuthProvider> {!authRoute && <NavBar />} <div className={authRoute ? '' : 'pt-12'}> <Component {...pageProps} /> </div> </AuthProvider> ); } 해당 부분에서 !authRoute 논리연산자를 추가하면 Error: Hydration failed because the initial UI does not match what was rendered on the server. 에러가 나옵니다. 강사님 파일을 클론 해서 빌드 확인해보니 이런 에러가 안나오길래, 이 강의까지의 나머지 파일도 클론한 것과 모두 같은 것을 확인했는데 왜 저만 이런 에러가 나오는걸까요? 해당 에러를 구글링해서 해결책으로 나오는 것들을 적용해봤는데 어느것도 에러를 해결해주지 못했습니다ㅠ 어떤 부분을 확인해보면 좋을까요?
배포단계와 보너스 강좌를 보면서 댓글 리트윗 , 좋아요 , 삭제 , 수정 및 리트윗한 게시글 다시 리트윗버튼을 클릭했을 때 해당 게시글을 지우려고 기능을 추가하려고 하고 있습니다 그래서 구조를 해당 리트윗 게시글을 me.Posts 안에서 리트윗한 아이디와 해당 게시글의 post.id가 일치하는 게시글을 삭제하려고하는데 해당 구조로 짜게 되면 맨처음 페이지가 로딩되고 나서 데이터를 받아오는 Post를 인식해서 그런지 리트윗 되어있던걸 삭제하는건 가능한데 삭제 후 다시 리트윗 하고 삭제하려면 id가 그 처음 리트윗되어있던 id를 찾습니다. (기존 리트윗 되어있던 post.id ) (리트윗 삭제 후 다시 리트윗 하고 나서 리트윗 버튼 클릭시 나오는 post.id ) 리트윗 제거하고 다시 리트윗 하면 DB와 me.Posts 와 mainPosts 안에 데이터가 새롭게 추가되는건 확인이 되는데 왜 초기 데이터값만을 읽는건지 모르겠습니다. 항상 늦은 시간에도 답변해주셔서 감사합니다.(그리고 워낙 질문이 많아서 죄송해요)
따라하며 배우는 노드, 리액트 시리즈 - 레딧 사이트 만들기(NextJS)(Pages Router)
- 학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! - 먼저 유사한 질문이 있었는지 검색해보세요. - 서로 예의를 지키며 존중하는 문화를 만들어가요. - 잠깐! 인프런 서비스 운영 관련 문의는 1:1 문의하기를 이용해주세요. 혹시 아래와 같이 자동완성 사용하는 거랑 같을까요??
따라하며 배우는 노드, 리액트 시리즈 - 레딧 사이트 만들기(NextJS)(Pages Router)
- 학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! - 먼저 유사한 질문이 있었는지 검색해보세요. - 서로 예의를 지키며 존중하는 문화를 만들어가요. - 잠깐! 인프런 서비스 운영 관련 문의는 1:1 문의하기를 이용해주세요. Eslint는 뭔지 알겠는데 밑에 3개는 처음보네요.. 업데이트 되면서 생긴건가요?? 마지막은 @components/* 이렇게 설정하라고 하던데 맞나요?? 무슨뜻인가요?? 구글링했습니다
따라하며 배우는 노드, 리액트 시리즈 - 레딧 사이트 만들기(NextJS)(Pages Router)
lllll@172 server % npm run dev > server@1.0.0 dev > env-cmd -f .env.development nodemon --exec ts-node ./src/server.ts [nodemon] 2.0.20 [nodemon] to restart at any time, enter rs [nodemon] watching path(s): . [nodemon] watching extensions: ts,json [nodemon] starting ts-node ./src/server.ts /Users/lllll/study/reddit-clone-app/server/node_modules/ts-node/src/index.ts:859 return new TSError(diagnosticText, diagnosticCodes, diagnostics); ^ TSError: ⨯ Unable to compile TypeScript: src/routes/subs.ts:139:16 - error TS2339: Property 'file' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'. 139 if (!req.file?.path) { ~~~~ src/routes/subs.ts:144:22 - error TS2339: Property 'file' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'. 144 unlinkSync(req.file.path); ~~~~ src/routes/subs.ts:154:26 - error TS2339: Property 'file' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'. 154 sub.imageUrn = req.file?.filename || ""; ~~~~ src/routes/subs.ts:157:27 - error TS2339: Property 'file' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'. 157 sub.bannerUrn = req.file?.filename || ""; ~~~~ at createTSError (/Users/lllll/study/reddit-clone-app/server/node_modules/ts-node/src/index.ts:859:12) at reportTSError (/Users/lllll/study/reddit-clone-app/server/node_modules/ts-node/src/index.ts:863:19) at getOutput (/Users/lllll/study/reddit-clone-app/server/node_modules/ts-node/src/index.ts:1077:36) at Object.compile (/Users/lllll/study/reddit-clone-app/server/node_modules/ts-node/src/index.ts:1433:41) at Module.m._compile (/Users/lllll/study/reddit-clone-app/server/node_modules/ts-node/src/index.ts:1617:30) at Module._extensions..js (node:internal/modules/cjs/loader:1308:10) at Object.require.extensions.<computed> [as .ts] (/Users/lllll/study/reddit-clone-app/server/node_modules/ts-node/src/index.ts:1621:12) at Module.load (node:internal/modules/cjs/loader:1117:32) at Function.Module._load (node:internal/modules/cjs/loader:958:12) at Module.require (node:internal/modules/cjs/loader:1141:19) { diagnosticCodes: [ 2339, 2339, 2339, 2339 ] } [nodemon] app crashed - waiting for file changes before starting... client에서는 rpm run dev가 정상적으로 실행되는데 server에서는 npm run dev를 실행하면 상기와 같은 오류가 발생하네요. 구글링해보니 server 디렉토리 내의 tsconfig.json 파일이 문제인 것 같은데 여러 세팅을 바꾸어보아도 해결되지않아 문의드립니다. (tsconfig.json 파일은 강사님이 올려주신 소스코드 파일과 같은 파일 사용중입니다)
{ "compilerOptions": { "baseUrl": "src" }, "include": ["src"] } keonhongkoo@keonhongui-MacBookAir frontend % yarn start yarn run v1.22.19 $ react-scripts start node:internal/modules/cjs/loader:1325 throw err; ^ SyntaxError: /Users/keonhongkoo/Desktop/instagram/frontend/jsconfig.json: Unexpected token / in JSON at position 75 at parse (<anonymous>) at Module._extensions..json (node:internal/modules/cjs/loader:1322:39) at Module.load (node:internal/modules/cjs/loader:1117:32) at Module._load (node:internal/modules/cjs/loader:958:12) at Module.require (node:internal/modules/cjs/loader:1141:19) at require (node:internal/modules/cjs/helpers:110:18) at getModules (/Users/keonhongkoo/Desktop/instagram/frontend/node_modules/react-scripts/config/modules.js:126:14) at Object.<anonymous> (/Users/keonhongkoo/Desktop/instagram/frontend/node_modules/react-scripts/config/modules.js:142:18) at Module._compile (node:internal/modules/cjs/loader:1254:14) at Module._extensions..js (node:internal/modules/cjs/loader:1308:10) Node.js v18.14.1 error Command failed with exit code 1. info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command. 이렇게 결과가 출력되는데 해결책이 안보이네요... vscode도 재시작해봤습니다ㅠ
http://practice.codebootcamp.co.kr/graphql 에서 mutation을 가져올때 백틱 안에 들어가면서 강사님과는 다른 포맷으로 입력됩니다. 데이터를 받아오는 과정에서 문제가 생기진 않는데 뒤의 수업에서 자동완성이 되지 않거나, # 주석도 표현되지않고 죄다 연두색으로 표현되는 문제가 있습니다. 왜 다르게 표현되는거죠? 강사님처럼 쉼표를 붙이고 자리를 똑같이 만들어도 변하지 않네요,,,
작성한 이유(저는 이 문제로 골머리를 앓았어서..) 도메인 설정 후 쿠키가 전달되지 않아 로그인이 되지 않았다가 해결되었습니다 session 설정 뿐만 아니라 nginx 설정도 확인해야 합니다 혹시라도 이 문제로 고통받으시는 분이 있다면 해결책이 되길 바랍니다 back 쪽 session 설정 if (process.env.NODE_ENV === "production") { app.use(morgan("combined")); app.use(hpp()); app.use(helmet()); app.set("trust proxy", 1); //배포 시 추가 app.use( cors({ origin: "https://engword.shop", //local "http://localhost:3000" credentials: true, }) ); } else { app.use(morgan("dev")); app.use( cors({ origin: true, credentials: true, }) ); } passportConfig(); app.use(express.json()); app.use(express.urlencoded({ extended: true })); app.use(cookieParser(process.env.COOKIE_SECRET)); app.use( session({ saveUninitialized: false, resave: false, secret: process.env.COOKIE_SECRET, proxy: true, //배포 시 추가 cookie: { httpOnly: true, secure: process.env.NODE_ENV === "production" ? true : false, //https 적용 시 true sameSite: process.env.NODE_ENV === "production" ? "none" : false, domain: process.env.NODE_ENV === "production" && ".engword.shop", }, }) ); nginx 설정 back 에서 설정한 nginx입니다 sudo vim /etc/nginx/nginx.conf server { server_name api.engword.shop; location / { proxy_set_header HOST $host; //추가 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header X-Real-IP $remote_addr; proxy_pass http://127.0.0.0:3000 //http로 설정할 것 proxy_redirect off; } //아래는 certbot 내용 } 위와 같이 설정을 바꾼 후 nginx를 다시 실행합니다 sudo systemctl restart nginx pm2 로 진행 시 pm2 를 껏다 키거나, pm2 재시작을 하시면 됩니다. pm2 껏다 키는 경우 sudo npx pm2 kill npm start (혹은 sudo npm start) pm2 재시작 sudo npx pm2 reload all
사용자 입력 예외처리를 하고 있는데, 1)문자 입력 시 오류 2)3자리 숫자가 아닐 경우 오류 다음과 같이 코드를 짰는데 1)의 경우 except 부분에서 "입력 오류"를 출력하지만 2)의 경우 "입력오류"가 출력되지 않고 그냥 재입력하게 되네요. 혹시 이유를 알 수 있나요? 또한 문자 입력 시 "숫자만 입력 가능합니다"를 출력 두자리수 입력 시 "세 자리 수를 입력하세요"를 출력 하도록 하려면 코드를 어떻게 수정해야 할까요? 감사합니다.! #세 자리 숫자만 입력할 수 있게 하는 함수 def input_check(msg, casting = int): while True: try: num = input(msg) # 사용자 입력 num_str = str(num) #맨 앞의 수가 0일경우 0이 잘려버리기 때문에 str을 따로 저장 if(casting(num) and len(num) == 3): return num_str except: print("입력 오류") continue