import java.util.Scanner;
public class MyApp {
public static void main(String[] args) {
String password;
do {
password = new Scanner(System.in).next();
} while (password.equals("d0t1nsta11") == false);
System.out.println("Password matched");
}
}
タグ: programming
Java 配列と反復処理
import java.util.Scanner;
public class MyApp {
public static void main(String[] args) {
int[] scores = {70, 90, 80, 60};
// System.out.println(scores[0]);
// System.out.println(scores[1]);
// System.out.println(scores[2]);
// for (int i = 0; i < 3; i++) {
for (int i = 0; i < scores.length; i++) {
System.out.println(scores[i]);
}
}
Java for
import java.util.Scanner;
public class MyApp {
public static void main(String[] args) {
for (int i = 0; i <= 10; i++){
System.out.println(i + " Hello");
}
}
}
Bootstrapフッターを配置
<!doctype html>
<html lang="ja">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<title>My Site</title>
</head>
<body>
<header class="bg-primary text-center text-light p-5">
<h1 class="fs-3">My Admin</h1>
</header>
<div class="container mt-5">
<section class="row">
<section class="col-md-4 mb-5">
こんにちは。こんにちは。こんにちは。こんにちは。こんにちは。こんにちは。こんにちは。こんにちは。こんにちは。こんにちは。こんにちは。こんにちは。
</section>
<section class="col-md-8">
こんにちは。こんにちは。こんにちは。こんにちは。こんにちは。こんにちは。こんにちは。こんにちは。こんにちは。こんにちは。こんにちは。こんにちは。
</section>
</section>
</div>
<footer class="bg-secondary text-center text-light p-5 mt-5">
(c) chodomeyuhei
</footer>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js"
integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW"
crossorigin="anonymous"></script>
</body>
</html>
python AIChatBOT
import re
import datetime
class Chatbot:
def __init__(self):
self.context = {}
self.history = []
self.user_name = None
self.current_intent = None # 現在の意図を保持
self.emotion_state = "neutral" # ユーザーの感情状態
self.long_term_memory = {} # ユーザーの好みなどを記憶する
# コンテキストと履歴を更新
def update_context(self, key, value):
self.context[key] = value
def add_to_history(self, user_input, bot_response):
self.history.append({"user": user_input, "bot": bot_response})
# 感情を分析
def analyze_emotion(self, user_input):
if re.search(r"疲れた|悲しい", user_input):
return "sad"
elif re.search(r"嬉しい|楽しい", user_input):
return "happy"
else:
return "neutral"
# 意図の認識
def intent_recognition(self, user_input):
if re.search(r"こんにちは|おはよう", user_input):
return "greeting"
elif re.search(r"名前は|あなたは誰", user_input):
return "identity"
elif re.search(r"ありがとう", user_input):
return "thanks"
elif re.search(r"天気|天候", user_input):
return "weather"
elif re.search(r"日付|時間", user_input):
return "time"
elif re.search(r"さようなら|バイバイ", user_input):
return "farewell"
elif re.search(r"趣味", user_input):
return "hobby"
elif re.search(r"タスク|予定", user_input):
return "task_management"
else:
return "unknown"
# 意図に応じた応答生成
def handle_intent(self, intent, user_input):
if intent == "greeting":
return self.greet_user()
elif intent == "identity":
return self.ask_for_name()
elif intent == "thanks":
return "どういたしまして!"
elif intent == "weather":
return self.get_weather()
elif intent == "time":
return self.get_time()
elif intent == "farewell":
return "さようなら!またお会いしましょう。"
elif intent == "hobby":
return self.ask_hobby()
elif intent == "task_management":
return self.manage_task()
else:
return "すみません、よくわかりません。もう一度お願いします。"
# 挨拶応答
def greet_user(self):
if self.user_name:
return f"こんにちは、{self.user_name}さん!今日はどうされましたか?"
else:
return "こんにちは!お名前を教えていただけますか?"
# 名前を聞く
def ask_for_name(self):
if not self.user_name:
self.current_intent = "ask_name"
return "私はあなたの名前をまだ聞いていませんね。教えていただけますか?"
else:
return f"あなたのお名前は{self.user_name}ですね!"
# 趣味について聞く
def ask_hobby(self):
if "hobby" not in self.long_term_memory:
self.current_intent = "ask_hobby"
return "趣味は何ですか?"
else:
hobby = self.long_term_memory['hobby']
return f"以前おっしゃった趣味は{hobby}ですね!"
# タスク管理(例: カレンダーに予定を追加)
def manage_task(self):
self.current_intent = "task_management"
return "新しい予定を追加したいのですか?詳細を教えてください。"
# 天気情報の取得(仮想)
def get_weather(self):
return "今日は晴れで、気温は22度です。"
# 日付・時間を取得
def get_time(self):
now = datetime.datetime.now()
return f"今は{now.strftime('%Y年%m月%d日 %H:%M:%S')}です。"
# 応答を感情に基づいて調整
def adjust_response_by_emotion(self, response):
if self.emotion_state == "sad":
return f"元気出してくださいね。{response}"
elif self.emotion_state == "happy":
return f"素晴らしいですね!{response}"
else:
return response
# 名前を更新
def update_name(self, user_input):
self.user_name = user_input
self.long_term_memory['name'] = user_input
# 趣味を保存
def update_hobby(self, user_input):
self.long_term_memory['hobby'] = user_input
# 応答のメインロジック
def chatbot_response(self, user_input):
if self.current_intent == "ask_name":
self.update_name(user_input)
return f"お名前は{self.user_name}さんですね!よろしくお願いします!"
elif self.current_intent == "ask_hobby":
self.update_hobby(user_input)
return f"{self.user_name}さんの趣味は{user_input}ですね!"
# 感情分析
self.emotion_state = self.analyze_emotion(user_input)
# 意図解析
intent = self.intent_recognition(user_input)
# 応答生成
response = self.handle_intent(intent, user_input)
# コンテキストと履歴の更新
self.add_to_history(user_input, response)
return self.adjust_response_by_emotion(response)
# チャットボットを実行
def run_chatbot():
chatbot = Chatbot()
# 初回挨拶
print("ボット: こんにちは!お名前を教えてください。")
while True:
user_input = input("あなた: ")
if user_input == "終了":
print("チャットを終了します。")
break
bot_response = chatbot.chatbot_response(user_input)
print("ボット: " + bot_response)
# チャットボットを実行
run_chatbot()
Java ペイントソフト
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.util.Stack;
import javax.imageio.ImageIO;
import java.io.File;
public class AdvancedPaintAppWithUndoRedo extends JFrame {
private DrawPanel drawPanel;
private Color currentColor = Color.BLACK;
private int brushSize = 4;
private String currentTool = "Brush";
private Stack<BufferedImage> undoStack = new Stack<>();
private Stack<BufferedImage> redoStack = new Stack<>();
public AdvancedPaintAppWithUndoRedo() {
setTitle("Advanced Paint Application with Undo/Redo");
setSize(800, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
drawPanel = new DrawPanel();
add(drawPanel, BorderLayout.CENTER);
// メニューバーの作成
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenuItem saveItem = new JMenuItem("Save");
JMenuItem openItem = new JMenuItem("Open");
JMenuItem clearItem = new JMenuItem("Clear");
saveItem.addActionListener(e -> saveImage());
openItem.addActionListener(e -> openImage());
clearItem.addActionListener(e -> drawPanel.clearCanvas());
fileMenu.add(saveItem);
fileMenu.add(openItem);
fileMenu.add(clearItem);
menuBar.add(fileMenu);
JMenu toolMenu = new JMenu("Tools");
JMenuItem colorItem = new JMenuItem("Choose Color");
JMenuItem brushItem = new JMenuItem("Brush Size");
JMenuItem toolBrush = new JMenuItem("Brush");
JMenuItem toolLine = new JMenuItem("Line");
JMenuItem toolRect = new JMenuItem("Rectangle");
JMenuItem toolOval = new JMenuItem("Oval");
JMenuItem toolText = new JMenuItem("Text");
colorItem.addActionListener(e -> chooseColor());
brushItem.addActionListener(e -> chooseBrushSize());
toolBrush.addActionListener(e -> currentTool = "Brush");
toolLine.addActionListener(e -> currentTool = "Line");
toolRect.addActionListener(e -> currentTool = "Rectangle");
toolOval.addActionListener(e -> currentTool = "Oval");
toolText.addActionListener(e -> currentTool = "Text");
toolMenu.add(colorItem);
toolMenu.add(brushItem);
toolMenu.add(toolBrush);
toolMenu.add(toolLine);
toolMenu.add(toolRect);
toolMenu.add(toolOval);
toolMenu.add(toolText);
menuBar.add(toolMenu);
JMenu editMenu = new JMenu("Edit");
JMenuItem undoItem = new JMenuItem("Undo");
JMenuItem redoItem = new JMenuItem("Redo");
undoItem.addActionListener(e -> drawPanel.undo());
redoItem.addActionListener(e -> drawPanel.redo());
editMenu.add(undoItem);
editMenu.add(redoItem);
menuBar.add(editMenu);
setJMenuBar(menuBar);
}
// メインメソッド
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
AdvancedPaintAppWithUndoRedo app = new AdvancedPaintAppWithUndoRedo();
app.setVisible(true);
});
}
// 色を選択する
private void chooseColor() {
Color color = JColorChooser.showDialog(null, "Choose a Color", currentColor);
if (color != null) {
currentColor = color;
drawPanel.setColor(color);
}
}
// ブラシサイズを選択する
private void chooseBrushSize() {
String sizeStr = JOptionPane.showInputDialog(this, "Enter brush size:", brushSize);
if (sizeStr != null) {
try {
int size = Integer.parseInt(sizeStr);
if (size > 0) {
brushSize = size;
drawPanel.setBrushSize(size);
}
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(this, "Invalid size entered.");
}
}
}
// 画像を保存する
private void saveImage() {
JFileChooser fileChooser = new JFileChooser();
if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
try {
ImageIO.write(drawPanel.getImage(), "png", file);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
// 画像を開く
private void openImage() {
JFileChooser fileChooser = new JFileChooser();
if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
try {
BufferedImage image = ImageIO.read(file);
drawPanel.setImage(image);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
// 描画用のパネル
class DrawPanel extends JPanel {
private BufferedImage image;
private Graphics2D g2;
private int startX, startY, endX, endY;
public DrawPanel() {
setPreferredSize(new Dimension(800, 600));
setDoubleBuffered(false);
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
startX = e.getX();
startY = e.getY();
if (g2 != null) {
if (currentTool.equals("Brush")) {
g2.fillOval(startX, startY, brushSize, brushSize);
}
saveToUndoStack();
}
repaint();
}
@Override
public void mouseReleased(MouseEvent e) {
endX = e.getX();
endY = e.getY();
if (g2 != null) {
switch (currentTool) {
case "Line":
g2.drawLine(startX, startY, endX, endY);
break;
case "Rectangle":
g2.drawRect(Math.min(startX, endX), Math.min(startY, endY),
Math.abs(startX - endX), Math.abs(startY - endY));
break;
case "Oval":
g2.drawOval(Math.min(startX, endX), Math.min(startY, endY),
Math.abs(startX - endX), Math.abs(startY - endY));
break;
case "Text":
String text = JOptionPane.showInputDialog("Enter text:");
if (text != null) {
g2.drawString(text, startX, startY);
}
break;
}
}
saveToUndoStack();
repaint();
}
});
addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseDragged(MouseEvent e) {
if (currentTool.equals("Brush")) {
g2.fillOval(e.getX(), e.getY(), brushSize, brushSize);
}
repaint();
}
});
clearCanvas();
}
// Undoスタックに現在の状態を保存
private void saveToUndoStack() {
BufferedImage undoImage = new BufferedImage(image.getWidth(), image.getHeight(), image.getType());
Graphics2D g = undoImage.createGraphics();
g.drawImage(image, 0, 0, null);
g.dispose();
undoStack.push(undoImage);
redoStack.clear(); // 新しいアクションの後、Redoをクリア
}
// Undo機能
public void undo() {
if (!undoStack.isEmpty()) {
redoStack.push(image);
image = undoStack.pop();
g2 = image.createGraphics();
repaint();
}
}
// Redo機能
public void redo() {
if (!redoStack.isEmpty()) {
undoStack.push(image);
image = redoStack.pop();
g2 = image.createGraphics();
repaint();
}
}
// 色を設定
public void setColor(Color color) {
if (g2 != null) {
g2.setColor(color);
}
}
// ブラシサイズを設定
public void setBrushSize(int size) {
brushSize = size;
}
// キャンバスをクリア
public void clearCanvas() {
image = new BufferedImage(800, 600, BufferedImage.TYPE_INT_ARGB);
g2 = image.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setPaint(Color.WHITE);
g2.fillRect(0, 0, image.getWidth(), image.getHeight());
g2.setPaint(Color.BLACK);
repaint();
}
// 描画イメージを取得
public BufferedImage getImage() {
return image;
}
// 描画イメージをセット
public void setImage(BufferedImage img) {
image = img;
g2 = image.createGraphics();
repaint();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (image != null) {
g.drawImage(image, 0, 0, null);
}
}
}
}
Java テキストエディタ
import javax.swing.*;
import javax.swing.undo.UndoManager;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.awt.dnd.*;
import java.awt.datatransfer.*;
public class AdvancedTextEditor extends JFrame implements ActionListener {
JTabbedPane tabbedPane;
JTextArea textArea;
JMenuBar menuBar;
JMenu fileMenu, editMenu, formatMenu, themeMenu;
JMenuItem newItem, openItem, saveItem, saveAllItem, closeItem;
JMenuItem cutItem, copyItem, pasteItem, findItem, replaceItem, undoItem, redoItem;
JMenuItem fontItem, lightThemeItem, darkThemeItem;
JFileChooser fileChooser;
JLabel statusBar;
UndoManager undoManager = new UndoManager();
JPopupMenu contextMenu;
public AdvancedTextEditor() {
setTitle("Advanced Text Editor");
setSize(800, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
tabbedPane = new JTabbedPane();
add(tabbedPane, BorderLayout.CENTER);
statusBar = new JLabel("Status: Ready | Line: 1, Column: 1");
add(statusBar, BorderLayout.SOUTH);
menuBar = new JMenuBar();
// ファイルメニューの作成
fileMenu = new JMenu("File");
newItem = new JMenuItem("New");
openItem = new JMenuItem("Open");
saveItem = new JMenuItem("Save");
saveAllItem = new JMenuItem("Save All");
closeItem = new JMenuItem("Close");
fileMenu.add(newItem);
fileMenu.add(openItem);
fileMenu.add(saveItem);
fileMenu.add(saveAllItem);
fileMenu.add(closeItem);
// 編集メニューの作成
editMenu = new JMenu("Edit");
cutItem = new JMenuItem("Cut");
copyItem = new JMenuItem("Copy");
pasteItem = new JMenuItem("Paste");
undoItem = new JMenuItem("Undo");
redoItem = new JMenuItem("Redo");
findItem = new JMenuItem("Find");
replaceItem = new JMenuItem("Replace");
editMenu.add(cutItem);
editMenu.add(copyItem);
editMenu.add(pasteItem);
editMenu.add(undoItem);
editMenu.add(redoItem);
editMenu.add(findItem);
editMenu.add(replaceItem);
// フォーマットメニューの作成
formatMenu = new JMenu("Format");
fontItem = new JMenuItem("Change Font");
formatMenu.add(fontItem);
// テーマメニューの作成
themeMenu = new JMenu("Themes");
lightThemeItem = new JMenuItem("Light Theme");
darkThemeItem = new JMenuItem("Dark Theme");
themeMenu.add(lightThemeItem);
themeMenu.add(darkThemeItem);
// メニューバーにメニューを追加
menuBar.add(fileMenu);
menuBar.add(editMenu);
menuBar.add(formatMenu);
menuBar.add(themeMenu);
setJMenuBar(menuBar);
// アクションリスナーの設定
newItem.addActionListener(this);
openItem.addActionListener(this);
saveItem.addActionListener(this);
saveAllItem.addActionListener(this);
closeItem.addActionListener(this);
cutItem.addActionListener(this);
copyItem.addActionListener(this);
pasteItem.addActionListener(this);
undoItem.addActionListener(this);
redoItem.addActionListener(this);
findItem.addActionListener(this);
replaceItem.addActionListener(this);
fontItem.addActionListener(this);
lightThemeItem.addActionListener(this);
darkThemeItem.addActionListener(this);
// ドラッグ&ドロップ対応
new DropTarget(tabbedPane, new FileDropHandler());
// コンテキストメニューの設定
contextMenu = new JPopupMenu();
contextMenu.add(cutItem);
contextMenu.add(copyItem);
contextMenu.add(pasteItem);
}
// アクションリスナーの処理
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == newItem) {
addNewTab();
}
// 他のアクションもここに追加
}
// 新しいタブを追加するメソッド
private void addNewTab() {
JTextArea textArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane(textArea);
tabbedPane.add("Untitled", scrollPane);
tabbedPane.setSelectedComponent(scrollPane);
textArea.getDocument().addUndoableEditListener(e -> undoManager.addEdit(e.getEdit()));
}
// ファイルドロップハンドラ
@SuppressWarnings("unchecked")
class FileDropHandler extends DropTargetAdapter {
@Override
public void drop(DropTargetDropEvent dtde) {
dtde.acceptDrop(DnDConstants.ACTION_COPY);
try {
java.util.List<File> droppedFiles = (java.util.List<File>) dtde.getTransferable()
.getTransferData(DataFlavor.javaFileListFlavor);
for (File file : droppedFiles) {
openFile(file);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
// ファイルを開くメソッド
private void openFile(File file) {
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
JTextArea textArea = new JTextArea();
textArea.read(reader, null);
JScrollPane scrollPane = new JScrollPane(textArea);
tabbedPane.add(file.getName(), scrollPane);
tabbedPane.setSelectedComponent(scrollPane);
} catch (IOException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
AdvancedTextEditor editor = new AdvancedTextEditor();
editor.setVisible(true);
});
}
}
ブックマークサイト.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ブックマークサイト</title>
<style>
:root {
--bg-color: #f4f4f9;
--text-color: #000;
--link-color: #007bff;
--btn-bg-color: #007bff;
--btn-hover-color: #0056b3;
--delete-btn-bg-color: #dc3545;
--delete-btn-hover-color: #c82333;
}
[data-theme="dark"] {
--bg-color: #2e2e2e;
--text-color: #fff;
--link-color: #66b2ff;
--btn-bg-color: #0056b3;
--btn-hover-color: #007bff;
--delete-btn-bg-color: #c82333;
--delete-btn-hover-color: #dc3545;
}
body {
font-family: Arial, sans-serif;
margin: 20px;
padding: 0;
background-color: var(--bg-color);
color: var(--text-color);
transition: background-color 0.3s, color 0.3s;
}
.container {
max-width: 800px;
margin: auto;
padding: 20px;
background: #fff;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
border-radius: 8px;
background-color: var(--bg-color);
color: var(--text-color);
transition: background-color 0.3s, color 0.3s;
}
.bookmark-form {
display: flex;
flex-direction: column;
gap: 10px;
margin-bottom: 20px;
}
.bookmark-form input, .bookmark-form select {
padding: 10px;
font-size: 16px;
border: 1px solid #ddd;
border-radius: 5px;
background-color: var(--bg-color);
color: var(--text-color);
}
.bookmark-form button {
padding: 10px;
font-size: 16px;
background-color: var(--btn-bg-color);
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
.bookmark-form button:hover {
background-color: var(--btn-hover-color);
}
.bookmark-list {
list-style-type: none;
padding: 0;
}
.bookmark-item {
display: flex;
justify-content: space-between;
align-items: center;
margin: 10px 0;
padding: 10px;
border: 1px solid #ddd;
border-radius: 5px;
background-color: #fafafa;
background-color: var(--bg-color);
color: var(--text-color);
}
.bookmark-item a {
text-decoration: none;
color: var(--link-color);
}
.bookmark-item button {
padding: 5px 10px;
font-size: 14px;
background-color: var(--delete-btn-bg-color);
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
.bookmark-item button:hover {
background-color: var(--delete-btn-hover-color);
}
.controls {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 20px;
}
</style>
</head>
<body data-theme="light">
<div class="container">
<h1>ブックマークサイト</h1>
<div class="controls">
<input type="text" id="search-bar" placeholder="ブックマークを検索" oninput="filterBookmarks()">
<select id="category-filter" onchange="filterByCategory()">
<option value="all">すべてのカテゴリー</option>
</select>
<button onclick="toggleTheme()">ダークモード切り替え</button>
</div>
<div class="bookmark-form">
<input type="text" id="bookmark-title" placeholder="タイトルを入力してください" required>
<input type="url" id="bookmark-url" placeholder="URLを入力してください" required>
<input type="text" id="bookmark-category" placeholder="カテゴリーを入力してください">
<button onclick="addBookmark()">ブックマークを追加</button>
</div>
<ul id="bookmark-list" class="bookmark-list"></ul>
</div>
<script>
document.addEventListener('DOMContentLoaded', loadBookmarks);
function loadBookmarks() {
const bookmarks = JSON.parse(localStorage.getItem('bookmarks')) || [];
const categories = new Set();
bookmarks.forEach(bookmark => {
renderBookmark(bookmark);
categories.add(bookmark.category);
});
updateCategoryFilter(Array.from(categories));
}
function addBookmark() {
const titleInput = document.getElementById('bookmark-title');
const urlInput = document.getElementById('bookmark-url');
const categoryInput = document.getElementById('bookmark-category');
const title = titleInput.value.trim();
const url = urlInput.value.trim();
const category = categoryInput.value.trim();
if (title === '' || url === '') {
alert('タイトルとURLを入力してください。');
return;
}
const bookmark = { title, url, category };
saveBookmark(bookmark);
renderBookmark(bookmark);
titleInput.value = '';
urlInput.value = '';
categoryInput.value = '';
updateCategoryFilter([category]);
}
function saveBookmark(bookmark) {
const bookmarks = JSON.parse(localStorage.getItem('bookmarks')) || [];
bookmarks.push(bookmark);
localStorage.setItem('bookmarks', JSON.stringify(bookmarks));
}
function renderBookmark(bookmark) {
const bookmarkList = document.getElementById('bookmark-list');
const listItem = document.createElement('li');
listItem.className = 'bookmark-item';
listItem.innerHTML = `
<span>${bookmark.title} (${bookmark.category})</span>
<div>
<a href="${bookmark.url}" target="_blank">訪問</a>
<button onclick="editBookmark('${bookmark.url}')">編集</button>
<button onclick="deleteBookmark('${bookmark.url}')">削除</button>
</div>
`;
bookmarkList.appendChild(listItem);
}
function deleteBookmark(url) {
let bookmarks = JSON.parse(localStorage.getItem('bookmarks')) || [];
bookmarks = bookmarks.filter(bookmark => bookmark.url !== url);
localStorage.setItem('bookmarks', JSON.stringify(bookmarks));
refreshBookmarkList();
}
function editBookmark(url) {
let bookmarks = JSON.parse(localStorage.getItem('bookmarks')) || [];
const bookmark = bookmarks.find(bookmark => bookmark.url === url);
if (bookmark) {
document.getElementById('bookmark-title').value = bookmark.title;
document.getElementById('bookmark-url').value = bookmark.url;
document.getElementById('bookmark-category').value = bookmark.category;
deleteBookmark(url); // 編集のために一旦削除
}
}
function refreshBookmarkList() {
const bookmarkList = document.getElementById('bookmark-list');
bookmarkList.innerHTML = '';
loadBookmarks();
}
function filterBookmarks() {
const query = document.getElementById('search-bar').value.toLowerCase();
const bookmarkItems = document.querySelectorAll('.bookmark-item');
bookmarkItems.forEach(item => {
const title = item.querySelector('span').innerText.toLowerCase();
item.style.display = title.includes(query) ? 'flex' : 'none';
});
}
function filterByCategory() {
const category = document.getElementById('category-filter').value;
const bookmarkItems = document.querySelectorAll('.bookmark-item');
bookmarkItems.forEach(item => {
const itemCategory = item.querySelector('span').innerText.split(' (')[1].slice(0, -1);
item.style.display = (category === 'all' || itemCategory === category) ? 'flex' : 'none';
});
}
function updateCategoryFilter(categories) {
const filter = document.getElementById('category-filter');
categories.forEach(category => {
if (![...filter.options].some(option => option.value === category)) {
const option = document.createElement('option');
option.value = category;
option.textContent = category;
filter.appendChild(option);
}
});
}
function toggleTheme() {
const body = document.body;
const currentTheme = body.getAttribute('data-theme');
const newTheme = currentTheme === 'light' ? 'dark' : 'light';
body.setAttribute('data-theme', newTheme);
}
</script>
</body>
</html>
Javascript 日時を更新してみよう
main.js
'use strict';
{
// 2000 4 11
// const d = new Date(2000, 3, 11);
// 2000 2 ??
const d = new Date(2000, 3, 0);
d.setDate(d.getDate() + 100);
console.log(d.toLocaleString());
}
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My JavaScript</title>
</head>
<body>
<script src="main.js"></script>
</body>
</html>
Solve the Two Sum problem in Python
Solve the Two Sum problem in Python
回答
Certainly, I’ll provide a solution to the Two Sum problem in Python. This problem is a common interview question where you’re given an array of integers and a target sum, and you need to find two numbers in the array that add up to the target.
Here’s a step-by-step approach:
- Use a Hash Map: This approach allows for O(n) time complexity, where n is the number of elements in the array.
- Iterate Through the Array: For each number, calculate what the other number should be to reach the target sum.
- Check if the Complement Exists: If the complement exists in the hash map, return the indices of both numbers.
Here’s the implementation:
python
def two_sum(nums, target): # Dictionary to store the number and its index num_dict = {} # Iterate through the list for i, num in enumerate(nums): # Calculate the complement complement = target - num # If the complement exists in the dictionary, return the indices if complement in num_dict: return [num_dict[complement], i] # If not, add the current number and its index to the dictionary num_dict[num] = i # If no solution is found, return an empty list or raise an exception return [] # or raise ValueError("No two sum solution") # Example usage nums = [2, 7, 11, 15] target = 9 result = two_sum(nums, target) print(result) # Should print [0, 1] because nums[0] + nums[1] == 9
Explanation:
- We use a dictionary (num_dict) to keep track of numbers we’ve seen and their indices.
- As we iterate through the list:
- We calculate what number, when added to the current number, would give us the target.
- If this number exists in our dictionary, we’ve found our pair, and we return their indices.
- If not, we add the current number and its index to the dictionary.
This solution ensures that we only traverse the list once, making it efficient with a time complexity of O(n). The space complexity is also O(n) in the worst case where all numbers are unique.