<!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>
カテゴリー: programming
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>
Here’s a brief overview of C++, one of the most powerful and widely used programming languages, especially in areas like game development, system programming, and high-performance applications:
Here’s a brief overview of C++, one of the most powerful and widely used programming languages, especially in areas like game development, system programming, and high-performance applications:
Overview of C++
- History: C++ was developed by Bjarne Stroustrup starting in 1979 at Bell Labs. It was designed as an extension of the C programming language, adding object-oriented, generic, and functional features.
- Key Features:
- Object-Oriented Programming (OOP): Supports encapsulation, inheritance, and polymorphism.
- Templates: Allows for generic programming, which is crucial for creating reusable code.
- Standard Template Library (STL): Provides a rich set of algorithms, containers, and iterators.
- Memory Management: Direct control over memory with new and delete, though modern C++ encourages smart pointers for safety.
- Performance: Known for its efficiency, close to the hardware, making it ideal for performance-critical applications.
- Syntax and Structure:
- C++ retains C’s syntax but adds features like classes, templates, and exceptions.
- Example of a simple C++ program:
cpp#include <iostream> int main() { std::cout << "Hello, World!" << std::endl; return 0; }
- Modern C++ (C++11, C++14, C++17, C++20):
- Introduced many features like auto, lambda expressions, move semantics, and more expressive syntax for containers and algorithms.
- Example of using auto and a lambda:
cpp#include <vector> #include <algorithm> int main() { std::vector<int> numbers = {1, 2, 3, 4, 5}; auto result = std::find_if(numbers.begin(), numbers.end(), [](int x) { return x > 3; }); if (result != numbers.end()) { std::cout << "First number greater than 3: " << *result << std::endl; } return 0; }
- Use Cases:
- Game Development: Used in engines like Unreal Engine.
- System Software: Operating systems, device drivers.
- High-Performance Computing: Scientific simulations, financial systems.
- Embedded Systems: Due to its efficiency and control over hardware.
- Learning C++:
- Start with basic C programming concepts.
- Learn object-oriented programming principles.
- Dive into templates and the STL.
- Understand modern C++ features for safer, more expressive code.
- Challenges:
- Complexity: C++ is vast with many features, which can be overwhelming for beginners.
- Memory Management: Manual memory handling can lead to bugs if not managed correctly.
If you have any specific questions about C++ or need help with a particular aspect of the language, feel free to ask!
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.
ruby 数当てゲーム
数当てゲーム
class NumberGuessingGame
attr_accessor :player_name, :target_number, :guess, :attempts, :difficulty, :games_played, :total_attempts
def initialize
@player_name = “”
@target_number = 0
@guess = nil
@attempts = 0
@difficulty = “easy”
@games_played = 0
@total_attempts = 0
end
def start
welcome_message
get_player_name
loop do
set_difficulty
setup_game
play_round
display_result
update_statistics
break unless play_again?
end
display_statistics
farewell_message
end
def welcome_message
puts “数当てゲームへようこそ!”
end
def get_player_name
print “あなたの名前を入力してください: “
@player_name = gets.chomp
end
def set_difficulty
puts “難易度を選択してください: easy, medium, hard”
@difficulty = gets.chomp.downcase
end
def setup_game
@target_number = case @difficulty
when “medium”
rand(1..500)
when “hard”
rand(1..1000)
else
rand(1..100)
end
@attempts = 0
end
def play_round
until @guess == @target_number
print “数を予想してください: “
@guess = gets.to_i
@attempts += 1
give_hint
end
end
def give_hint
if @guess < @target_number puts “もっと大きい数です。” elsif @guess > @target_number
puts “もっと小さい数です。”
else
puts “正解です!”
end
end
def display_result
puts “#{@player_name}さん、おめでとうございます!”
puts “#{@attempts}回目で正解です!”
end
def play_again?
print “もう一度プレイしますか?(yes/no): “
answer = gets.chomp.downcase
answer == ‘yes’
end
def update_statistics
@games_played += 1
@total_attempts += @attempts
end
def display_statistics
puts “統計情報:”
puts “プレイしたゲーム数: #{@games_played}”
puts “総試行回数: #{@total_attempts}”
puts “平均試行回数: #{@total_attempts / @games_played}” if @games_played > 0
end
def farewell_message
puts “ゲームをプレイしていただきありがとうございました!またお会いしましょう!”
end
end
ゲーム開始
game = NumberGuessingGame.new
game.start
機能概要
難易度選択: プレイヤーはeasy, medium, hardのいずれかの難易度を選択でき、難易度によって予想する数の範囲が変わります。
easy: 1-100
medium: 1-500
hard: 1-1000
プレイ統計の表示: プレイしたゲーム数、総試行回数、平均試行回数を表示します。
再プレイ機能: プレイヤーはゲーム終了後、再度プレイするかどうかを選択できます。
実行方法
上記のコードをファイル(例: number_guessing_game_extended.rb)として保存します。
ターミナル(コマンドプロンプト)を開き、そのファイルがあるディレクトリに移動します。
以下のコマンドを実行してゲームを開始します。
bash
ruby number_guessing_game_extended.rb
この拡張版では、より多くの機能を楽しむことができ、プレイヤーは複数回のゲームプレイを通じて自分のパフォーマンスを追跡することができます。
PHP 変数
<?php
// echo 150 * 120 . PHP_EOL;
// echo 150 * 130 . PHP_EOL;
// echo 150 * 140 . PHP_EOL;
$price = 150;
echo $price * 120 . PHP_EOL;
echo $price * 130 . PHP_EOL;
echo $price * 140 . PHP_EOL;
PHP 数値
<?php
echo 10 + 3 . PHP_EOL;
echo 10 - 3 . PHP_EOL;
echo 10 * 3 . PHP_EOL;
echo 10 ** 3 . PHP_EOL;
echo 10 / 3 . PHP_EOL;
echo 10 % 3 . PHP_EOL;
echo 10 + 2 * 3 . PHP_EOL;
echo (10 + 2) * 3 . PHP_EOL;