검색결과 리스트
프로그래밍에 해당되는 글 335건
- 2023.02.09 프로그래머스 JAVA 폰켓몬
- 2023.02.09 프로그래머스 레벨0 안전지대(C#, JAVA) try catch(Exception e)
- 2023.02.09 다항식 더하기 JAVA
- 2023.02.07 프로그래머스 레벨2 C# 주차 요금 계산(array.where)
- 2023.02.06 프로그래머스 C# 푸드 파이트 대회(for문, 문자열 합하기, P, J)
- 2023.02.06 프로그래머스 C# 신고 결과 받기(Dictionary, HashMap, P, J)
- 2023.02.06 프로그래머스 C# 콜라 문제(P, J)
- 2023.02.06 프로그래머스 C# 없는 숫자 더하기(P, J)
글
프로그래머스 JAVA 폰켓몬
import java.util.*;
class Solution {
public int solution(int[] nums) {
int answer = 0;
int pick = nums.length / 2;
HashSet<Integer> set = new HashSet<>(); // 중복저장이 안되는 해시셋
for(int n : nums)
{
set.add(n); // 헤시셋에 추가한다.
}
if(pick >= set.size())
answer = set.size(); //폰켓몬 종류보다 고를 수 있는 수가 많으면 그냥 그대로 폰켓몬 수를 대입한다.
else
answer = pick; // 그렇지 않으면 픽할 수 있는 수를 대입한다.
return answer;
}
}
// 자바는 처음이라 솔직히 다른 사람 거를 봤다.
'프로그래밍' 카테고리의 다른 글
프로그래머스 C# 예상 대진표(JAVA) (0) | 2023.02.11 |
---|---|
프로그래머스 문자열 내의 p와 y의 개수(JAVA, toLowerCase().split(""), equals) (0) | 2023.02.11 |
프로그래머스 레벨0 안전지대(C#, JAVA) try catch(Exception e) (0) | 2023.02.09 |
다항식 더하기 JAVA (0) | 2023.02.09 |
프로그래머스 레벨2 C# 주차 요금 계산(array.where) (0) | 2023.02.07 |
글
프로그래머스 레벨0 안전지대(C#, JAVA) try catch(Exception e)
public class Solution {
public int solution(int[][] param) {
int safeZone = 0;
// 위험지역 Set
for (int i = 0; i < param.length; i++)
{
for (int j = 0; j < param.length; j++)
{
if (param[i][j] == 1)
setArea(param, i, j);
}
}
// 안전지역 Count
for (int i = 0; i < param.length; i++)
{
for (int j = 0; j < param.length; j++)
{
if (param[i][j] == 0)
safeZone++;
}
}
return safeZone;
}
void setArea(int[][] param, int x, int y) {
for (int i = -1; i < 2; i++)
{
for (int j = -1; j < 2; j++)
{
try
{
if (param[x + i][y + j] == 0)
param[x + i][y + j] = 2;
}
catch (Exception e)
{
}
}
}
}
}
public class Solution {
int[][] d = {{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 0}, {0, 1}, {1, -1}, {1, 0}, {1, 1}};
public int solution(int[][] board) {
int n = board.length;
boolean[][] unable = new boolean[n][n];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (board[i][j] == 1)
{
for (int[] k: d)
{
int nearX = i + k[0];
int nearY = j + k[1];
if (nearX >= 0 && nearX < n && nearY >= 0 && nearY < n)
{
unable[nearX][nearY] = true;
}
}
}
}
}
int unableCount = 0;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (unable[i][j])
{
unableCount++;
}
}
}
return n * n - unableCount;
}
}
////////////////////////
public class Solution {
public int solution(int[,] board) {
int answer = 0;
int length = board.GetLength(0);
int[] x = new int[8]{-1, 1, 0, 0, -1, -1, 1, 1};
int[] y = new int[8]{0, 0, -1, 1, -1, 1, -1, 1};
int[,] temp = new int[length,length];
int nx = 0;
int ny = 0;
for(int i = 0; i < length; i++)
{
for(int j = 0; j < length; j++)
{
if(board[i,j] == 1)
{
temp[i,j] = 1;
for(int k = 0; k < 8; k++)
{
nx = i + x[k];
ny = j + y[k];
if(nx >= 0 && nx < length && ny >= 0 && ny < length)
{
temp[nx,ny] = 1;
}
}
}
}
}
for(int i = 0; i < length; i++)
{
for(int j = 0; j < length; j++)
{
if(temp[i,j] != 1)
{
answer++;
}
}
}
return answer;
}
}
////////////////////////
C#
using System;
public class Solution {
public int solution(int[,] board) {
int safeZone = 0;
// 위험지역 Set
for (int i = 0; i < board.GetLength(0); i++)
{
for (int j = 0; j < board.GetLength(1); j++)
{
if (board[i,j] == 1)
setArea(board, i, j);
}
}
// 안전지역 Count
for (int i = 0; i < board.GetLength(0); i++)
{
for (int j = 0; j < board.GetLength(1); j++)
{
if (board[i,j] == 0)
safeZone++;
}
}
return safeZone;
}
void setArea(int[,] board, int x, int y) {
for (int i = -1; i < 2; i++)
{
for (int j = -1; j < 2; j++)
{
try
{
if (board[x + i,y + j] == 0)
board[x + i,y + j] = 2;
}
catch (Exception e)
{
}
}
}
}
}
//// try catch(Exception e)를 활용해서 어레이의 범위를 벗어나는 경우를 빠져나오게 하는 방식이다.
/// 그리고 폭탄의 영향 범위 지역을 2로 세팅해서 safezone의 숫자를 계산할 수 있도록 설정했다.
'프로그래밍' 카테고리의 다른 글
프로그래머스 문자열 내의 p와 y의 개수(JAVA, toLowerCase().split(""), equals) (0) | 2023.02.11 |
---|---|
프로그래머스 JAVA 폰켓몬 (0) | 2023.02.09 |
다항식 더하기 JAVA (0) | 2023.02.09 |
프로그래머스 레벨2 C# 주차 요금 계산(array.where) (0) | 2023.02.07 |
프로그래머스 C# 푸드 파이트 대회(for문, 문자열 합하기, P, J) (0) | 2023.02.06 |
글
다항식 더하기 JAVA
class Solution {
public String solution(String polynomial) {
String answer = "";
int x_num = 0;
int constant = 0;
String[] words = polynomial.split("\\+");
for( int i = 0 ; i < words.length ; i++ )
{
String word = words[i].trim();
System.out.println( word );
if( word.endsWith("x") )
{
if( word.length() == 1 ) x_num += 1;
else x_num += Integer.parseInt( word.substring( 0, word.length() - 1 ) );
}
else
constant += Integer.parseInt( word );
}
if ( x_num == 0 )
answer = String.valueOf( constant );
else if( constant == 0 )
{
if( x_num == 1 ) answer = "x";
else answer = x_num + "x";
}
else if ( constant == 0 && x_num == 0 )
answer = "0";
else
{
if( x_num == 1 ) answer = "x + " + constant;
else answer = x_num + "x + " + constant;
}
return answer;
}
}
C#
using System;
public class Solution {
public string solution(string polynomial) {
string answer = "";
string temp = "";
string[] str = polynomial.Split(" ");
int xNum = 0;
int num = 0;
for(int i = 0; i < str.Length; i+=2)
{
// Contains()을 활용해 str[i]에 x가 있는지 확인
if(str[i].Contains("x"))
{
// temp에 str[i].Replace를 활용해 x를 string.Empty로 초기화
temp = str[i].Replace("x", string.Empty);
// temp에 값이 없으면 xNum에 1을 더함
if(temp == "")
{
xNum += 1;
}
// temp에 값이 있으면 xNum에 int형으로 변환후 더함
else
{
xNum += int.Parse(temp);
}
}
else
{
num += int.Parse(str[i]);
}
}
if(num == 0)
{
if(xNum == 1)
{
answer = "x";
}
else
{
answer = xNum.ToString() + "x";
}
}
else
{
if(xNum == 0)
{
answer = num.ToString();
}
else if(xNum == 1)
{
answer = "x " + "+ " + num.ToString();
}
else
{
answer = xNum.ToString() + "x " + "+ " + num.ToString();
}
}
return answer;
}
}
'프로그래밍' 카테고리의 다른 글
프로그래머스 JAVA 폰켓몬 (0) | 2023.02.09 |
---|---|
프로그래머스 레벨0 안전지대(C#, JAVA) try catch(Exception e) (0) | 2023.02.09 |
프로그래머스 레벨2 C# 주차 요금 계산(array.where) (0) | 2023.02.07 |
프로그래머스 C# 푸드 파이트 대회(for문, 문자열 합하기, P, J) (0) | 2023.02.06 |
프로그래머스 C# 신고 결과 받기(Dictionary, HashMap, P, J) (0) | 2023.02.06 |
글
프로그래머스 레벨2 C# 주차 요금 계산(array.where)
using System;
using System.Collections.Generic;
using System.Linq;
public class Solution {
public int[] solution(int[] fees, string[] records) {
List<string> newRecords = new List<string>();
Dictionary<string, List<string>> dicList = new Dictionary<string, List<string>>();
List<int> answerList = new List<int>();
for (var i=0; i< records.Length; i++)
{
var tmp = records[i].Split(' ');
var list = records.Where(w => w.Substring(6, 4) == tmp[1]).OrderBy(o => o);
if(!dicList.ContainsKey(tmp[1]))
{
dicList.Add(tmp[1], list.ToList());
}
}
var result = dicList.OrderBy(o => o.Key);
double totalMinute = 0;
foreach(var dic in result)
{
DateTime inTime = DateTime.Now;
DateTime outTime = DateTime.Now;
for (var i=0;i< dic.Value.Count;i++ )
{
var time = dic.Value[i].Split(' ')[0];
var gb = dic.Value[i].Split(' ')[2];
if (gb == "IN")
{
inTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " " + time);
}
else
{
outTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " " + time);
TimeSpan dateDiff = outTime - inTime;
totalMinute += Convert.ToInt32(dateDiff.TotalMinutes);
}
}
// 출차기록이 없으면 23:59 분 출차로 기록
if (dic.Value.Count % 2 != 0)
{
outTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " 23:59");
TimeSpan dateDiff2 = outTime - inTime;
totalMinute += Convert.ToInt32(dateDiff2.TotalMinutes);
}
double parkingPrice = 0;
if (totalMinute <= fees[0])
{
parkingPrice = fees[1];
}
else
{
parkingPrice = fees[1] + Math.Ceiling((totalMinute - fees[0]) / fees[2]) * fees[3];
}
answerList.Add(Convert.ToInt32(parkingPrice));
totalMinute = 0;
}
var answer = answerList.ToArray();
return answer;
}
}
//////////////////
using System;
using System.Collections.Generic;
using System.Linq;
public class Solution {
public int[] solution(int[] fees, string[] records) {
List<string> cars = new List<string>();
Dictionary<string, int> recDic = new Dictionary<string, int>();
Dictionary<string, int> tempDic = new Dictionary<string, int>();
for(int i = 0; i < records.Length; i++)
{
string[] rec = records[i].Split(' ');
if(rec[2] == "IN")
{
int inTime = int.Parse(rec[0].Substring(0, 2)) * 60 + int.Parse(rec[0].Substring(3, 2));
if(!recDic.ContainsKey(rec[1]))
{
cars.Add(rec[1]);
tempDic.Add(rec[1], inTime);
}
else
tempDic[rec[1]] = inTime;
}
else
{
int outTime = int.Parse(rec[0].Substring(0, 2)) * 60 + int.Parse(rec[0].Substring(3, 2));
if(!recDic.ContainsKey(rec[1]))
recDic.Add(rec[1], outTime - tempDic[rec[1]]);
else
recDic[rec[1]] += outTime - tempDic[rec[1]];
tempDic[rec[1]] = -1;
}
}
cars.Sort();
int[] answer = new int[cars.Count];
for(int i = 0; i < cars.Count; i++)
{
int time = 0;
if(!recDic.TryGetValue(cars[i], out time) || tempDic[cars[i]] != -1)
time += 1439 - tempDic[cars[i]];
answer[i] = fees[1];
if(time > fees[0])
{
time -= fees[0];
answer[i] += (time / fees[2]) * fees[3];
if(time % fees[2] != 0)
answer[i] += fees[3];
}
}
return answer;
}
}
'프로그래밍' 카테고리의 다른 글
프로그래머스 레벨0 안전지대(C#, JAVA) try catch(Exception e) (0) | 2023.02.09 |
---|---|
다항식 더하기 JAVA (0) | 2023.02.09 |
프로그래머스 C# 푸드 파이트 대회(for문, 문자열 합하기, P, J) (0) | 2023.02.06 |
프로그래머스 C# 신고 결과 받기(Dictionary, HashMap, P, J) (0) | 2023.02.06 |
프로그래머스 C# 콜라 문제(P, J) (0) | 2023.02.06 |
글
프로그래머스 C# 푸드 파이트 대회(for문, 문자열 합하기, P, J)
using System;
using System.Linq;
public class Solution {
public string solution(int[] food) {
string answer = "";
int times = 0;
for(int i = 1; i<food.Length;i++)
{
times = food[i]/2;
for(int j = 0;j<times;j++)
{
answer += i;
}
}
answer += 0;
for(int i = food.Length-1; i>0;i--)
{
times = food[i]/2;
for(int j = 0;j<times;j++)
{
answer += i;
}
}
return answer;
}
}
////////////////
using System;
using System.Linq;
public class Solution {
public string solution(int[] food) {
string answer = "0";
int times = 0;
for (int i = food.Length - 1; i > 0; i--)
{
for (int j = 0; j < food[i] / 2; j++)
{
answer = i + answer + i;
}
}
return answer;
}
}
using System;
using System.Collections.Generic;
public class Solution
{
public string solution(int[] food)
{
string answer = "";
for(int i = 1; i < food.Length; i++)
{
int nowCount = food[i] / 2;
for(int count = 0; count < nowCount; count++)
{
answer += i.ToString();
}
}
char[] temp = answer.ToCharArray();
Array.Reverse(temp);
string back = new string(temp);
answer += "0" + back;
return answer;
}
}
파이썬
/////
def solution(food):
answer ="0"
for i in range(len(food)-1, 0,-1):
c = int(food[i]/2)
while c>0:
answer = str(i) + answer + str(i)
c -= 1
return answer
////
def solution(food):
answer = ''
rev=''
for i in range(1,len(food)):
answer+=str(i)*(food[i]//2)
rev=answer[::-1]
answer+='0'
return answer+rev
자바
/////
class Solution {
public String solution(int[] food) {
String answer = "0";
for (int i = food.length - 1; i > 0; i--)
{
for (int j = 0; j < food[i] / 2; j++)
{
answer = i + answer + i;
}
}
return answer;
}
}
'프로그래밍' 카테고리의 다른 글
다항식 더하기 JAVA (0) | 2023.02.09 |
---|---|
프로그래머스 레벨2 C# 주차 요금 계산(array.where) (0) | 2023.02.07 |
프로그래머스 C# 신고 결과 받기(Dictionary, HashMap, P, J) (0) | 2023.02.06 |
프로그래머스 C# 콜라 문제(P, J) (0) | 2023.02.06 |
프로그래머스 C# 없는 숫자 더하기(P, J) (0) | 2023.02.06 |
글
프로그래머스 C# 신고 결과 받기(Dictionary, HashMap, P, J)
using System;
using System.Collections;
using System.Collections.Generic;
public class Solution
{
public int[] solution(string[] id_list, string[] report, int k)
{
int[] answer = new int[id_list.Length];
Dictionary<string, List<string>> dic = new Dictionary<string, List<string>>();
for (int i = 0; i < report.Length; i++)
{
string[] str = report[i].Split(' ');
string give = str[0];
string take = str[1];
if (!dic.ContainsKey(take))
{
List<string> list = new List<string>();
list.Add(give);
dic.Add(take, list);
continue;
}
if (!dic[take].Contains(give))
{
dic[take].Add(give);
}
}
for (int i = 0; i < id_list.Length; i++)
{
foreach (KeyValuePair<string, List<string>> item in dic)
{
if (item.Value.Contains(id_list[i]))
{
if (item.Value.Count >= k)
{
answer[i] = ++answer[i];
}
}
}
}
return answer;
}
}
//딕셔너리의 활용이 중요하다.
using System;
using System.Linq;
public class Solution {
public int[] solution(string[] id_list, string[] report, int k) {
int[] answer = new int[id_list.Length]; // 결과 배열.
int[] receive = new int[id_list.Length]; // 신고받은 횟수.
int[] send = new int[id_list.Length]; // 신고한 횟수.
report = report.Distinct().ToArray();
// 중복 삭제하기
// 신고받은 횟수를 기록.
for (int i = 0; i < report.Length; i++)
{
string report_str = report[i].Split(' ')[1];
int report_index = Array.IndexOf(id_list, report_str);
// 신고받은 인덱스 횟수
receive[report_index]++;
}
// 신고받은 횟수가 k보다 높을 시 answer 값을 상승.
for (int i = 0; i < report.Length; i++)
{
string report_str = report[i].Split(' ')[1];
int report_index = Array.IndexOf(id_list, report_str);
if (receive[report_index] >= k)
{
string send_str = report[i].Split(' ')[0];
int send_index = Array.IndexOf(id_list, send_str);
answer[send_index]++;
}
}
return answer;
}
}
using System;
using System.Linq;
using System.Collections.Generic;
public class Solution {
public int[] solution(string[] id_list, string[] report, int k) {
var tReport = report.Distinct().
Select(s => s.Split(' ')).
GroupBy(g => g[1]).
Where(w => w.Count() >= k).
SelectMany(sm => sm.Select(s => s[0])).
ToList();
return id_list.ToDictionary(x => x, x => tReport.Count(c => x == c)).Values.ToArray();
}
}
파이썬
//////
def solution(id_list, report, k):
answer = [0] * len(id_list)
reports = {x : 0 for x in id_list}
for r in set(report):
reports[r.split()[1]] += 1
for r in set(report):
if reports[r.split()[1]] >= k:
answer[id_list.index(r.split()[0])] += 1
return answer
def solution(id_list, report, k):
answer = [0] * len(id_list)
dic_report = {id: [] for id in id_list} # 해당 유저를 신고한 ID
for i in set(report):
i = i.split()
dic_report[i[1]].append(i[0])
for key, value in dic_report.items():
if len(value) >= k:
for j in value:
answer[id_list.index(j)] += 1
return answer
자바
//////
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
class Solution {
public int[] solution(String[] id_list, String[] report, int k) {
List<String> list = Arrays.stream(report).distinct().collect(Collectors.toList());
HashMap<String, Integer> count = new HashMap<>();
for (String s : list)
{
String target = s.split(" ")[1];
count.put(target, count.getOrDefault(target, 0) + 1);
}
return Arrays.stream(id_list).map(_user -> {
final String user = _user;
List<String> reportList = list.stream().filter(s -> s.startsWith(user + " ")).collect(Collectors.toList());
return reportList.stream().filter(s -> count.getOrDefault(s.split(" ")[1], 0) >= k).count();
}).mapToInt(Long::intValue).toArray();
}
}
///////
import java.util.*;
class Solution {
public int[] solution(String[] id_list, String[] report, int k) {
// key: 신고당한놈, value: 몇명한테 당했는지
Map<String, Set<String>> map = new HashMap<>();
for (String rep : report)
{
String[] arr = rep.split(" ");
Set<String> set = map.getOrDefault(arr[1], new HashSet<>());
set.add(arr[0]);
map.put(arr[1], set);
}
// key: 알림받을 놈, value: 몇번 알림받을지
Map<String, Integer> countMap = new LinkedHashMap<>();
for (String id : id_list)
{
countMap.put(id, 0);
}
for (Map.Entry<String, Set<String>> entry : map.entrySet())
{
if (entry.getValue().size() >= k)
{ // 정지당할놈
for (String value : entry.getValue())
{
countMap.put(value, countMap.getOrDefault(value, 0) + 1);
}
}
}
return countMap.values().stream().mapToInt(Integer::intValue).toArray();
}
}
'프로그래밍' 카테고리의 다른 글
프로그래머스 레벨2 C# 주차 요금 계산(array.where) (0) | 2023.02.07 |
---|---|
프로그래머스 C# 푸드 파이트 대회(for문, 문자열 합하기, P, J) (0) | 2023.02.06 |
프로그래머스 C# 콜라 문제(P, J) (0) | 2023.02.06 |
프로그래머스 C# 없는 숫자 더하기(P, J) (0) | 2023.02.06 |
프로그래머스 C# 성격 유형 검사하기(파이썬, 자바) dictionary (0) | 2023.02.05 |
글
프로그래머스 C# 콜라 문제(P, J)
using System;
public class Solution {
public int solution(int a, int b, int n) {
int answer = 0;
int index = n;
while(n > n%a)
{
answer += (n/a)*b;
n = n%a+(n/a)*b;
}
return answer;
}
}
/////
public class Solution {
public int solution(int a, int b, int n) {
return (n > b ? n - b : 0) / (a - b) * b;
}
}
파이썬
//////
def solution(a, b, n):
answer = 0
while n >= a:
answer += (n // a) * b
n = (n // a) * b + (n % a)
return answer
자바
class Solution {
public int solution(int a, int b, int n) {
int answer = 0;
while (n >= a)
{
answer += b * (n / a);
n = b * (n / a) + n % a;
}
return answer;
}
}
'프로그래밍' 카테고리의 다른 글
프로그래머스 C# 푸드 파이트 대회(for문, 문자열 합하기, P, J) (0) | 2023.02.06 |
---|---|
프로그래머스 C# 신고 결과 받기(Dictionary, HashMap, P, J) (0) | 2023.02.06 |
프로그래머스 C# 없는 숫자 더하기(P, J) (0) | 2023.02.06 |
프로그래머스 C# 성격 유형 검사하기(파이썬, 자바) dictionary (0) | 2023.02.05 |
프로그래머스 레벨1 C# 삼총사(3중 for문, 파이썬, 자바) (0) | 2023.02.05 |
글
프로그래머스 C# 없는 숫자 더하기(P, J)
using System;
public class Solution {
public int solution(int[] numbers) {
int sum = 0;
for(int i = 0;i<numbers.Length;i++)
{
sum += numbers[i];
}
return 45-sum;
}
}
//////
using System;
using System.Collections.Generic;
using System.Linq;
public class Solution {
public int solution(int[] numbers) {
var numberArray = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
return numberArray.Except(numbers).Sum();
}
}
파이썬
def solution(numbers):
return 45 - sum(numbers)
자바
class Solution {
public int solution(int[] numbers) {
int sum = 45;
for (int i : numbers) {
sum -= i;
}
return sum;
}
}
'프로그래밍' 카테고리의 다른 글
프로그래머스 C# 신고 결과 받기(Dictionary, HashMap, P, J) (0) | 2023.02.06 |
---|---|
프로그래머스 C# 콜라 문제(P, J) (0) | 2023.02.06 |
프로그래머스 C# 성격 유형 검사하기(파이썬, 자바) dictionary (0) | 2023.02.05 |
프로그래머스 레벨1 C# 삼총사(3중 for문, 파이썬, 자바) (0) | 2023.02.05 |
프로그래머스 C# 나머지가 1이 되는 수 찾기(파이썬, 자바) (0) | 2023.02.05 |